//数据链路层数据的访问,可以得到以太网头,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 {
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 底端