原始套接字-TCP/IP下三层数据显示

 1 #include <stdio.h>
 2 #include <errno.h>
 3 #include <unistd.h>
 4 #include <sys/socket.h>
 5 #include <sys/types.h>
 6 #include <linux/in.h>
 7 #include <linux/if_ether.h>
 8 
 9 int main(int argc, char **argv)
10 {
11     int sock, n;
12     char buffer[2048];
13     unsigned char *iphead, *ethhead;
14 
15     if ( (sock=socket(PF_PACKET, SOCK_RAW, htons(ETH_P_IP)))<0) ///建立套接字。PF_PACKET:底层包访问协议;SOCK_RAW:提供原始网络协议访问;
16     {
17         perror("socket");
18         exit(1);
19     }
20 
21     while (1)
22     {
23         printf("----------
");
24         n = recvfrom(sock,buffer,2048,0,NULL,NULL);///接收数据包
25         printf("%d bytes read
",n);
26         /* Check to see if the packet contains at least
27          *      * complete Ethernet (14), IP (20) and TCP/UDP
28          *           * (8) headers.
29          *                */
30         if (n<42)
31         {
32             perror("recvfrom():");
33             printf("Incomplete packet (errno is %d)
",errno);
34             close(sock);
35             exit(0);
36         }
37         ethhead = buffer;
38         ///打印顺序可以通过wireshark包分析出来!!!
39         printf("Source MAC address:%02x:%02x:%02x:%02x:%02x:%02x
",ethhead[6],ethhead[7],ethhead[8],ethhead[9],ethhead[10],ethhead[11]);
40         printf("Destination MAC address: %02x:%02x:%02x:%02x:%02x:%02x
",ethhead[0],ethhead[1],ethhead[2],ethhead[3],ethhead[4],ethhead[5]);
41 
42         iphead = buffer+14; /* Skip Ethernet header */
43         if (*iphead==0x45)
44         {
45             /* Double check for IPv4 and no options present */
46             printf("Source host %d.%d.%d.%d
",iphead[12],iphead[13],iphead[14],iphead[15]);
47             printf("Dest host %d.%d.%d.%d
",iphead[16],iphead[17],iphead[18],iphead[19]);
48             ///这里只是取协议的前四个字节
49             printf("Source %d ,Dest ports %d
",(iphead[20]<<8)+iphead[21],(iphead[22]<<8)+iphead[23]);///端口占两个字节所以要使高位左移8位然后再加上低位值
50             printf("Layer-4 protocol %d
",iphead[9]);
51         }
52     }
53 
54 }

输出:

----------
74 bytes read
Source MAC address:48:8a:d2:12:59:ec
Destination MAC address: 00:21:6a:85:2c:8c
Source host 220.181.57.232
Dest host 192.168.0.118
Souce port front:80 ,Dest port front:80 ----
Source 80 ,Dest ports 59472
Layer-4 protocol 6

原文地址:https://www.cnblogs.com/A--Q/p/7149746.html