socket pcap 抓包代码

本文介绍了一个使用libpcap库捕获特定ARP数据包的C程序。程序通过设置过滤器来筛选目标MAC地址的数据包,并详细展示了如何解析并打印接收到的数据包内容。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pcap.h>

#define MAXBYTES2CAPTURE 2048

void process_packet(u_char *arg, const struct pcap_pkthdr *pkthdr,
        const u_char *packet)
{
    int i = 0, *counter = (int *)arg;

    printf("packet count:%d\n", ++(*counter));
    printf("received packet size %d\n", pkthdr->len);

    printf("payload\n");
    for (i = 0; i < pkthdr->len; i++)
    {
        printf("%02x ", (unsigned int)packet[i]);

        if ((i % 16 == 15 && i != 0) || (i == pkthdr->len-1))
            printf("\n");
    }
    printf("\n\n**************\n");
    return;           
}

int main(int argc, char *argv[])
{
    int i = 0, count = 0;
    pcap_t *descr = NULL;
    char errbuf[PCAP_ERRBUF_SIZE], *device = NULL;
    bpf_u_int32 netaddr = 0, mask = 0;
    struct bpf_program filter;

    memset(errbuf, 0, sizeof(errbuf));

    if (argc != 2)
        device = pcap_lookupdev(errbuf);
    else
        device = argv[1];

    printf("Try to open device %s\n", device);

   
    if ((descr = pcap_open_live(device, MAXBYTES2CAPTURE, 1, 0, errbuf)) == NULL )
    {
        printf("error:%s\n", errbuf);
        exit(-1);
    }
    printf("pcap_open\n");

    pcap_lookupnet(device, &netaddr, &mask, errbuf);
    printf("pcap_look\n");

    //if (pcap_compile(descr, &filter, "arp and ether host 00:0c:29:b7:f6:33", 0, mask) < 0)
    if (pcap_compile(descr, &filter, "arp and ether host 00:0c:29:cd:d6:dd", 0, mask) < 0)
    {
        printf("pcap_compile error\n");
        exit(-1);
    }
    printf("compile\n");
    pcap_setfilter(descr, &filter);
    printf("setfilter\n");

    pcap_loop(descr, 3, process_packet, (u_char *)&count);

    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值