使用Libpcap库捕获局域网中的IP包

本文介绍了如何利用Libpcap库捕获局域网中的IP包,具体要求包括:显示数据包的源/目的MAC地址、源/目的IP地址、上层协议类型。对于TCP或UDP协议,还将打印端口号及数据的16进制与ASCII表示,不可打印字符用'.'替代。
摘要由CSDN通过智能技术生成

要求

内容
使用Libpcap库捕获局域网中的IP包,要求:
1、打印数据包的源与目的物理地址;
2、打印源IP与目的IP地址;
3、打印出上层协议类型;
4、如果上层协议为TCP或UDP协议,打印目的与源端口信息;
5、如果上层协议为TCP或UDP协议,将数据以16进制与ASCII的两种方式同时打印出来,不可打印字符以‘.’代替;
00000 47 45 54 20 2f 20 48 54 54 50 2f 31 2e 31 0d 0a GET / HTTP/1.1…

参考链接

  1. libpcap使用 - htttw的专栏 - CSDN博客
    https://blog.csdn.net/htttw/article/details/7521053
  2. 网络字节序与主机字节序的相互转换 - Dablelv的博客专栏 - CSDN博客
    https://blog.csdn.net/K346K346/article/details/79053136
  3. 网络包几种格式ethhdr、ether_header、iphdr、tcphdr、udphdr - fangxin205的专栏 - CSDN博客
    https://blog.csdn.net/fangxin205/article/details/54613226

代码


#include<stdio.h>
#include<string.h>
#include<sys/types.h>
#include<sys/time.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<netinet/in_systm.h>
#include<netinet/ip.h>
#include<netinet/if_ether.h>
#include<netinet/tcp.h>
#include<netinet/udp.h>
#include<pcap.h>
#include<netdb.h>
#include<time.h>
#include<sys/time.h>
#include<stdlib.h>
#include<ctype.h>
 
//打印16进制和ascii
void print(u_char*payload,int len,int offset,int maxlen)
{
   
	printf("%.5x  ",offset);	//打印偏移量(宽度为5)
	int max=maxlen;	//数据包的有效载荷和长度
	int i;
	for(i=0;i<16;i++)	//打印16个字节的16进制payload
	{
   
		if((len-i)>0)	//还没打完
		{
   
			printf("%.2x ",payload[max-(len-i)]);
		}
		else	//已打完,最后一个后面有空格
		{
   
			printf("   ");
		}
	}
	printf("	");
	for(i=0;i<16;i++)	//打印16个字节的asciipayload
	{
   
		if(isprint(payload[max-(len-i)]))	//为可打印字符
		{
   
			printf("%c",payload[max-(len-i)]);
		}
		else		//打印不出来的用"."表示
		{
   
			printf(".");
		}
	}
}
 
//打印数据包
void print_data(u_char *payload,int len)
{
   
	int line_width=16;	//一行16个字节
	int len_rem=len;	//剩余长度
	int maxlen=len;		//数据包的有效载荷和长度
	int offset=0;		//偏移量
	while(1)
	{
   
		if(len_rem<line_width)	//最后一次打印
		{
   
			if(len_rem==0)	//已打印完
			{
   	break;	}
			
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值