Linux数据链路层的访问

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

 1 #include <stdio.h>
  2 #include <sys/socket.h>
  3 #include <sys/ioctl.h>
  4 #include <linux/if_ether.h>
  5 #include <net/if.h>
  6 #include <netinet/in.h>
  7 #include <linux/ip.h>
  8 #include <linux/tcp.h>
  9 #include <linux/udp.h>
 10 #include <string.h>
 11 #include <arpa/inet.h>
 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         底端


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

浪游东戴河

你就是这个世界的唯一

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值