Linux数据链路层的访问

//数据链路层数据的访问,可以得到以太网头,ip头,tcp头和udp头(省略)

 1 #include
  2 #include
  3 #include
  4 #include
  5 #include
  6 #include
  7 #include
  8 #include
  9 #include
 10 #include
 11 #include
 12
 13
 14 int main(void)
 15 {

 16         int fd;

 17         fd = socket(AF_INET, SOCK_PACKET, htons(0x0003));

//0x0003表示数据帧类型不确定;ip:0x0800 arp:0x0806

 18         char *ethname = "wlan0";//网络接口
 19         struct ifreq ifr;
 20         int i;
 21         strcpy(ifr.ifr_name, ethname);
 22         i = ioctl(fd, SIOCGIFFLAGS, &ifr);
 23         if(i< 0)
 24         {
 25                 close(fd);
 26                 perror("can't get flags \n");
 27                 return -1;
 28         }
 29         ifr.ifr_flags |= IFF_PROMISC; //监听其他网卡数据,设置为混杂模式
 30         i = ioctl(fd, SIOCSIFFLAGS, &ifr);
 31         if(i< 0)
 32         {
 33                 perror("promiscuous set error");
 34                 return -2;
 35         }
 36         
 37         char ef[ETH_FRAME_LEN];
 38         struct ethhdr *p_ethhdr;
 39         int n;
 40

41         struct iphdr* p_iphdr;
 42         char temp[64];
 43
 44 while(1)
 45 {
 46         n = read(fd, ef, ETH_FRAME_LEN);
 47         p_ethhdr = (struct ethhdr *)ef;
 48         if(n > 0)
 49                 printf("read some data :%d...\n", n);
 50         printf("dest MAC...\n");
 51
 52         for(i=0; i < ETH_ALEN -1; i++)
 53                 printf("%02x-", p_ethhdr->h_dest[i]);
 54         printf("%02x \n", p_ethhdr->h_dest[ETH_ALEN-1]);
 55         for(i=0; i < ETH_ALEN -1; i++)
 56                 printf("%02x-", p_ethhdr->h_source[i]);
 57         printf("%02x \n", p_ethhdr->h_source[ETH_ALEN-1]);
 58
 59         printf("protocol: 0x%04x", ntohs(p_ethhdr->h_proto));
 60         if(ntohs(p_ethhdr->h_proto) == 0x0800)
 61         {
 62                 p_iphdr = (struct iphdr *)(ef + ETH_HLEN);
 63                 inet_ntop(AF_INET, &(p_iphdr->saddr), temp, sizeof(temp));
 64                 printf("src ip: %s\n", temp);
 65
 66                 inet_ntop(AF_INET, &(p_iphdr->daddr), temp, sizeof(temp));
 67                 printf("dest ip: %s\n", temp);
 68
 69         }
 70
 71         sleep(2);
 72 }
 73         return 0;
 74 }
                                                                                                                                     74,1         底端


你可能感兴趣的:(Linux数据链路层的访问)