linux 下抓包

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <linux/if_ether.h>
#include <linux/in.h>


struct iphdr
  {
    unsigned int ihl:4;
    unsigned int version:4;
    u_int8_t tos;
    u_int16_t tot_len;
    u_int16_t id;
    u_int16_t frag_off;
    u_int8_t ttl;
    u_int8_t protocol;
    u_int16_t check;
    u_int32_t saddr;
    u_int32_t daddr;
  };



void show(char*str,int len)
{
	int i=0;
	for(i=0;i<len;i++)
	{
		int temp=str[i]&0x0ff;
		printf("%x ",temp);
	}
	printf("\n");
}

void int2str(char*buf,int ip)
{
	int str[4];
	str[0]=(int)ip&0x0FF;
	str[1]=(int)(ip>>8)&0x0FF;
	str[2]=(int)(ip>>16)&0x0FF;
	str[3]=(int)(ip>>24)&0x0FF;
	sprintf(buf,"%d.%d.%d.%d",str[0],str[1],str[2],str[3]);
}
#define BUFFER_MAX 65536
int main()
{
	int len;
	char buff[BUFFER_MAX]={0};
	struct ethhdr arpH;
	struct iphdr ipH;
	struct sockaddr_in addr;
	char ip[20];
	int sockId = socket(PF_PACKET, SOCK_RAW, htons(ETH_P_IP));
	// ARP package
	//int sockId = socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ARP));

	if(sockId<0)
	{
		printf("create error!\n");
		return -1;
	}
	while(1)
	{
		//arp Package
		len = recvfrom(sockId, buff, BUFFER_MAX, 0, NULL, NULL);
		if(len>0)
		{
			printf("length:%d\n",len);
			memcpy(&arpH,buff,14);
			printf("type:0x%x\n",arpH.h_proto);
			if(arpH.h_proto==8)
			{
				printf("------IP------\n");
				memcpy(&ipH,buff+14,sizeof(ipH));
				int2str(ip,ipH.daddr);
				printf("da address:%s\n",ip);
				int2str(ip,ipH.saddr);
				printf("sa address:%s\n",ip);
				printf("protocol:%d\n",ipH.protocol);
				if(ipH.protocol==1)
				{
					printf("ICMP\n");
				}
				else if(ipH.protocol==6)
				{
					printf("TCP\n");
				}
				else if(ipH.protocol==17)
				{
					printf("UDPn");
				}
			}
		}
	}
	close(sockId);
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值