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
) {
17 if (0>(sock
=socket(PF_PACKET
, SOCK_RAW
, htons(ETH_P_IP
)))) {
23 strncpy(ethreq
.ifr_name
,"eth0",IFNAMSIZ
);
24 if(-1 == ioctl(sock
,SIOCGIFFLAGS
,ðreq
)){
29 ethreq
.ifr_flags
|=IFF_PROMISC
;
30 if(-1 == ioctl(sock
,SIOCGIFFLAGS
,ðreq
)){
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
));