pcap收包并过滤

 

#include <pcap.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <net/ethernet.h>
#include <linux/if_ether.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <netinet/tcp.h>
#include <stdint.h>
#include <sys/socket.h>
#include <arpa/inet.h>

/*
void proc_eth()
{}

void proc_ip()
{}

void proc_udp()
{}

void proc_tcp()
{}

void proc_http()
{}
*/

void proc_packet(uint8_t *para, const struct pcap_pkthdr *pkthdr,
const uint8_t *data)
{
struct ether_header *eth = NULL;
struct iphdr *ip = NULL;
struct tcphdr *tcp = NULL;

eth = (struct ether_header *)(data + 0);
if(eth->ether_type != htons(ETHERTYPE_IP) )
{
return;
}

ip = (struct iphdr *)(data + ETH_HLEN);
if (ip->protocol != IPPROTO_TCP)
{
return;
}

tcp = (struct tcphdr *)(data + ETH_HLEN + ip->ihl * 4);

if (tcp->source == htons(80) || tcp->dest == htons(80) )
{
struct in_addr srcip, destip;
memcpy(&srcip, &(ip->saddr), sizeof(struct in_addr) );
memcpy(&destip, &(ip->daddr), sizeof(struct in_addr) );
fprintf(stderr, "src: %-15s:%-4u\tdest: %-15s:%-4u\n",
inet_ntoa(srcip), ntohs(tcp->source),
inet_ntoa(destip), ntohs(tcp->dest) );
}
/*
proc_res(ip, tcp, (char *)(data + ETH_HLEN + ip->ihl * 4 + tcp->doff * 4),
ntohs(ip->tot_len) - ip->ihl * 4 - tcp->doff * 4);
*/
};

int main()
{
char errbuf[PCAP_ERRBUF_SIZE];
char *device = "eth0";
pcap_t * pcap;

/*
device = pcap_lookupdev(errbuf);
if (device == NULL)
{
printf("pcap lookup device err: %s\n", errbuf);
exit(1);
}
*/

pcap = pcap_open_live(device, 1500, 1, -1, errbuf);
if (pcap == NULL)
{
printf("pcap open err: %s\n", errbuf);
exit(1);
}

if (pcap_loop(pcap, -1, proc_packet, NULL) == -1)
{
printf("pcap set callback function error.\n");
exit(1);
}

while(1)
{
sleep(10);
}

//pcap_close(pcap);
exit(0);
}



转载于:https://www.cnblogs.com/tiantao/archive/2012/03/15/2398574.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值