【Linux网络编程(八)】分析TCP、UDP报文

在这里插入图片描述

#include <stdio.h>
#include <sys/socket.h>
#include <netinet/ehter.h>
#include <arpa/inet.h>

int mian(int argc, char const *argv[])
{
	int sockfd = socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ALL));
	printf("sockfd = %d\n",sockfd);
	
	//接收数据
	while(1)
	{
		unsigned char buf[1500] = "";
		int len = recvfrom(sockfd, buf, sizeof(buf), 0, NULL, NULL);
		printf("len = %d\n", len); 
		
		//分析mac报文
		char src_mac[18] = "";   //源mac
		char dst_mac[18] = "";   //目的mac

		sprintf(dst_mac,"%02x:%02x:%02x:%02x:%02x:%02x",\
						buf[0],buf[1],buf[2],buf[3],buf[4],buf[5]);
		sprintf(src_mac,"%02x:%02x:%02x:%02x:%02x:%02x",\
						buf[0+6],buf[1+6],buf[2+6],buf[3+6],buf[4+6],buf[5+6]);
		unsigned short mac_type = 0;
		mac_type = ntohs(*(unsigned short *)(buf + 12));
		printf("%s-->%s:",src_mac,dst_mac);
		if(mac_type == 0x0800)
		{
			printf("IP报文\n");
			unsigned char *ip_p = buf+14;
			int ip_head_len = ((*ip_p)&0x0f)*4; //从第一个字节里取ip长度
			char src_ip[16] = "";
			char dst_ip[16] = "";
			inet_ntop(AF_INET, (void *)ip_p+12, src_ip, 16);
			inet_ntop(AF_INET, (void *)ip_p+12, dst_ip, 16);

			printf("\t%s--->%s:", stc_ip, dst_ip);
			char ip_type = *(ip_p+9);
			if(ip_type == 1)
			{
				printf("ICMP报文"\n");
			}
			else if(ip_type == 2)
			{
				printf("IGMP报文"\n");
			}
			else if(ip_type == 6)
			{
				printf("TCP报文\n");
				unsigned char *tcp_p = buf+14+ip_head_len;
				printf("\t%hu--->%hu:", ntohs(*(unsigned short *)tcp_p),\
				ntohs(*(unsigned short *)(tcp_p+2)));

				int tcp_head_len = ((*(tcp_p +12))>>4)*4;
				//应用数据
				printf("%s\n", tcp_p+tcp_head_len);
			}
			else if(ip_type == 17)
			{
				printf("UDP报文\n");
				unsigned char *tcp_p = buf+14+ip_head_len;
				printf("\t%hu--->%hu:", ntohs(*(unsigned short *)udp_p),\
				ntohs(*(unsigned short *)(udp_p+2)));
				//应用数据
				printf("%s\n", udp_p+8);
			}
			else{
				printf("未知报文\n");
			}
			
		}
		else if(mac_type == 0x0806)
		{
			printf("ARP报文\n");
		}
		else if(mac_type == 0x8035)
		{
			printf("RARP报文\n");
		}
		else
		{
			printf("其他报文\n");
		}
			

		
	}

	close(sockfd);
	
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Eiker_3169

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值