push sockt&epoll samples
[socket_samples.git] / epoll / ip_snif.c
blobe38944eb1b06bec83934c6ac91b4767fe6910ac9
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <errno.h>
4 #include <unistd.h>
5 #include <sys/types.h>
6 #include <sys/socket.h>
7 #include <netinet/in.h>
8 #include <netinet/ip.h>
9 #include <netinet/if_ether.h>
11 int main(int argc, char **argv) {
12 int sock, n;
13 char buffer[2048];
14 struct ethhdr *eth;
15 struct iphdr *iph;
17 if (0>(sock=socket(PF_PACKET, SOCK_RAW, htons(ETH_P_IP)))) {
18 perror("socket");
19 exit(1);
21 //混杂模式
22 struct ifreq ethreq;
23 strncpy(ethreq.ifr_name,"eth0",IFNAMSIZ);
24 if(-1 == ioctl(sock,SIOCGIFFLAGS,&ethreq)){
25 perror("ioctl");
26 close(sock);
27 exit(1);
29 ethreq.ifr_flags |=IFF_PROMISC;
30 if(-1 == ioctl(sock,SIOCGIFFLAGS,&ethreq)){
31 perror("ioctl");
32 close(sock);
33 exit(1);
36 while (1) {
37 printf("=====================================\n");
38 //注意:在这之前我没有调用bind函数,原因是什么呢?
39 n = recvfrom(sock,buffer,2048,0,NULL,NULL);
40 printf("%d bytes read\n",n);
42 //接收到的数据帧头6字节是目的MAC地址,紧接着6字节是源MAC地址。
43 eth=(struct ethhdr*)buffer;
44 printf("Dest MAC addr:%02x:%02x:%02x:%02x:%02x:%02x\n",eth->h_dest[0],eth->h_dest[1],eth->h_dest[2],eth->h_dest[3],eth->h_dest[4],eth->h_dest[5]);
45 printf("Source MAC addr:%02x:%02x:%02x:%02x:%02x:%02x\n",eth->h_source[0],eth->h_source[1],eth->h_source[2],eth->h_source[3],eth->h_source[4],eth->h_source[5]);
47 iph=(struct iphdr*)(buffer+sizeof(struct ethhdr));
48 //我们只对IPV4且没有选项字段的IPv4报文感兴趣
49 if(iph->version ==4 && iph->ihl == 5){
50 printf("Source host:%s\n",inet_ntoa(iph->saddr));
51 printf("Dest host:%s\n",inet_ntoa(iph->daddr));