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

时间:2023-03-09 13:23:28
原始套接字-TCP/IP下三层数据显示
 #include <stdio.h>
#include <errno.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <linux/in.h>
#include <linux/if_ether.h> int main(int argc, char **argv)
{
int sock, n;
char buffer[];
unsigned char *iphead, *ethhead; if ( (sock=socket(PF_PACKET, SOCK_RAW, htons(ETH_P_IP)))<) ///建立套接字。PF_PACKET:底层包访问协议;SOCK_RAW:提供原始网络协议访问;
{
perror("socket");
exit();
} while ()
{
printf("----------\n");
n = recvfrom(sock,buffer,,,NULL,NULL);///接收数据包
printf("%d bytes read\n",n);
/* Check to see if the packet contains at least
* * complete Ethernet (14), IP (20) and TCP/UDP
* * (8) headers.
* */
if (n<)
{
perror("recvfrom():");
printf("Incomplete packet (errno is %d)\n",errno);
close(sock);
exit();
}
ethhead = buffer;
///打印顺序可以通过wireshark包分析出来!!!
printf("Source MAC address:%02x:%02x:%02x:%02x:%02x:%02x\n",ethhead[],ethhead[],ethhead[],ethhead[],ethhead[],ethhead[]);
printf("Destination MAC address: %02x:%02x:%02x:%02x:%02x:%02x\n",ethhead[],ethhead[],ethhead[],ethhead[],ethhead[],ethhead[]); iphead = buffer+; /* Skip Ethernet header */
if (*iphead==0x45)
{
/* Double check for IPv4 and no options present */
printf("Source host %d.%d.%d.%d\n",iphead[],iphead[],iphead[],iphead[]);
printf("Dest host %d.%d.%d.%d\n",iphead[],iphead[],iphead[],iphead[]);
///这里只是取协议的前四个字节
printf("Source %d ,Dest ports %d\n",(iphead[]<<)+iphead[],(iphead[]<<)+iphead[]);///端口占两个字节所以要使高位左移8位然后再加上低位值
printf("Layer-4 protocol %d\n",iphead[]);
}
} }

输出:

----------
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