1. 程式人生 > >原始套接字-TCP/IP下三層數據顯示

原始套接字-TCP/IP下三層數據顯示

pf_packet printf linu 0.11 pes span close double ddr

 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("----------\n"); 24 n = recvfrom(sock,buffer,2048
,0,NULL,NULL);///接收數據包 25 printf("%d bytes read\n",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)\n",errno); 34 close(sock); 35 exit(0); 36 } 37 ethhead = buffer; 38 ///打印順序可以通過wireshark包分析出來!!! 39 printf("Source MAC address:%02x:%02x:%02x:%02x:%02x:%02x\n",ethhead[6],ethhead[7],ethhead[8],ethhead[9],ethhead[10],ethhead[11]); 40 printf("Destination MAC address: %02x:%02x:%02x:%02x:%02x:%02x\n",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\n",iphead[12],iphead[13],iphead[14],iphead[15]); 47 printf("Dest host %d.%d.%d.%d\n",iphead[16],iphead[17],iphead[18],iphead[19]); 48 ///這裏只是取協議的前四個字節 49 printf("Source %d ,Dest ports %d\n",(iphead[20]<<8)+iphead[21],(iphead[22]<<8)+iphead[23]);///端口占兩個字節所以要使高位左移8位然後再加上低位值 50 printf("Layer-4 protocol %d\n",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

原始套接字-TCP/IP下三層數據顯示