linux原始套接字编程之收发链路层广播(收端)



#include
#include
#include
#include

#include
#include

#include
#include
#include

#include
#include

#include

#define ETH_ALEN 6
#define ETH_P_GATE 0x9006
#define ETH_MAX_DATA_LEN 1488

#define ETH_HEAD_LEN 16
#define ETH_BODY_LEN 1496
#define ETH_LEN ETH_HEAD_LEN + ETH_BODY_LEN

struct EtherHead
{
 unsigned char   dest[ETH_ALEN];   /* destinat    ion eth addr */
 unsigned char   source[ETH_ALEN]; /* source e    ther addr    */
 unsigned int    proto;        /* packet type     ID field */
};

struct EtherBody
{
 size_t datalen;
 char data[ETH_MAX_DATA_LEN];
};

int main()
{
 //创建原始套接字
 int sock = socket(PF_PACKET, SOCK_RAW, htons(ETH_P_GATE));
 if (0 > sock)
 {
  printf("create_sock err %s",  strerror(errno));
  return -1;
 }
 
 //获取网卡信息
 struct ifreq ifr;
 memset(&ifr, 0, sizeof(struct ifreq));
 memcpy(ifr.ifr_name, "eth0", strlen("eth0") + 1);
 ifr.ifr_ifindex = if_nametoindex(ifr.ifr_name);
 
 struct sockaddr_ll sk_ll;
 sk_ll.sll_family = AF_PACKET;
 sk_ll.sll_protocol = htons(ETH_P_GATE);
 sk_ll.sll_hatype = 1;
 sk_ll.sll_halen = ETH_ALEN;
 sk_ll.sll_pkttype = PACKET_MULTICAST;
 sk_ll.sll_ifindex = ifr.ifr_ifindex;//指定网卡
 
 if(0 < bind(sock, (struct sockaddr *)&sk_ll, sizeof(struct sockaddr_ll)))
 {
  printf("bind err %s", strerror(errno));
  exit(0);
 } 

 void *buf = malloc(1512);
 struct sockaddr_in recv;
 socklen_t recvlen = 0;
 while(1)
 {
  if(-1 == recvfrom(sock, buf, 1512, 0, (struct sockaddr *)&recv,  &recvlen))
  {
   printf("sendto err %s",  strerror(errno));
   exit(-1);
  }
  //struct EtherBody *eth = NULL;
  //memcpy(eth, buf+ETH_HEAD_LEN, ETH_BODY_LEN);
  //printf("%s\n", eth->data);
  printf("data:%s\n", ((struct EtherBody *)(buf+ETH_HEAD_LEN))->data);
  sleep(1);
 }
}

你可能感兴趣的:(linux编程)