WinPcap/Npcap 桥接网络,应编那种规则筛选收取的以太网帧?

155 篇文章 1 订阅
61 篇文章 3 订阅
该代码段展示了如何使用libpcap库打开一个网络设备,设置为混杂模式,读取超时,并创建一个过滤器来捕获特定的以太网帧。它确保了捕获整个包,设置了数据方向为只接收,并优化了响应速度。过滤器旨在捕获特定MAC地址或广播帧。
摘要由CSDN通过智能技术生成
    inline static pcap_t* pcap_live_open_packet_device(struct pcap_if* pcap, int readTimeout) {
        char errbuf[PCAP_ERRBUF_SIZE];
        if (!pcap) {
            return NULL;
        }

        pcap_t* device = pcap_open_live(
            pcap->name, // name of the device
            65536, // portion of the packet to capture
                   // 65536 guarantees that the whole packet
                   // will be captured on all the link layers
            PCAP_OPENFLAG_PROMISCUOUS | // promiscuous mode
            PCAP_OPENFLAG_NOCAPTURE_LOCAL | PCAP_OPENFLAG_MAX_RESPONSIVENESS,
            readTimeout, // read timeout
            errbuf); // error buffer
        if (!device) {
            return NULL;
        }

        /* Must is ethernet */
        int datalink = pcap_datalink(device);
        if (datalink != DLT_EN10MB && datalink != DLT_EN3MB) {
            pcap_live_close_packet_device(device);
            return NULL;
        }

        /* Only capture IN */
        pcap_setdirection(device, PCAP_D_IN);

        /* We want any responses back ASAP */
        if (pcap_setmintocopy(device, 0)) {
            pcap_live_close_packet_device(device);
            return NULL;
        }

        bpf_u_int32 netmask = ETHERNET_MASK;
        if (netmask == INADDR_ANY) {
            netmask = INADDR_NONE;
        }

        char rules[8096];
        sprintf(rules, "ether dst %02x:%02x:%02x:%02x:%02x:%02x or ether dst ff:ff:ff:ff:ff:ff",
            ETHERNET_MAC.s_data[0],
            ETHERNET_MAC.s_data[1],
            ETHERNET_MAC.s_data[2],
            ETHERNET_MAC.s_data[3],
            ETHERNET_MAC.s_data[4],
            ETHERNET_MAC.s_data[5]);

        /* Compile the filter */
        struct bpf_program fcode;
        if (pcap_compile(device, &fcode, rules, 1, netmask)) {
            pcap_live_close_packet_device(device);
            return NULL;
        }

        /* Set the filter */
        if (pcap_setfilter(device, &fcode)) {
            pcap_live_close_packet_device(device);
            return NULL;
        }
        return device;
    }

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值