是否可以检查接口是否在 pcap 中激活?

Is it possible to check if an interface is activated in pcap?

我正在使用 pcap.h 制作一个基本的数据包嗅探器。当我对调用 pcap_dispatch 的函数进行单元测试时,我给了它非激活接口和无效接口。 pcap_dispatch return -3,就 pcap_dispatch 的手册页而言,它应该只有 return -2、-1 或更多,但绝不会更少。

当然,我可以在 pcap_dispatch returns 之后处理这个 -3 return 值,将其作为一些模糊的边缘情况处理,但我想确保它从来没有 return 这样的值。

只有当我知道如何检查接口是否被激活时,我才能用断言来做到这一点。那么,有人知道吗?


pcap_t *null_iface = NULL;
pcap_t *not_act = pcap_create( "valid", errmsg );
pcap_t *act = pcap_create( "valid", errmsg );
    pcap_activate( act );
pcap_t *not_act_inv = pcap_create( "invalid", errmsg );
pcap_t *act_inv = pcap_create( "invalid", errmsg );
    pcap_activate( act );
pcap_t *ifaces[ 5 ] = {
    null_iface, not_act, act, not_act_inv, act_inv 
    };

for ( int a = 0; a < 5; a++ ) {
    result = pcap_dispatch( iface[ a ], 1, handler, NULL );
    // if one    - got one
    // elif zero - got nothing
    // elif -1   - error ( doesn't fire, by the way )
    // elif -2   - I manually stopped it
    // else      - impossible - but the assert fires
    //           - printing result is -3
    //           - for not_act, not_act_inv, and act_inv
    else {
        assert( false );
    }
}

Is it possible to check if an interface is activated in pcap?

是的。您可以通过查看 pcap_activate() 的 return 值来检查。 pcap_activate() 手册页说:

pcap_activate() returns 0 on success without warnings, PCAP_WARNING_PROMISC_NOTSUP on success on a device that doesn't support promiscuous mode if promiscuous mode was requested, PCAP_WARNING on success with any other warning, PCAP_ERROR_ACTIVATED if the handle has already been activated, PCAP_ERROR_NO_SUCH_DEVICE if the capture source specified when the handle was created doesn't exist, PCAP_ERROR_PERM_DENIED if the process doesn't have permission to open the capture source, PCAP_ERROR_RFMON_NOTSUP if monitor mode was specified but the capture source doesn't support monitor mode, PCAP_ERROR_IFACE_NOT_UP if the capture source is not up, and PCAP_ERROR if another error occurred. If PCAP_WARNING or PCAP_ERROR is returned, pcap_geterr() or pcap_perror() may be called with p as an argument to fetch or display a message describing the warning or error. If PCAP_WARNING_PROMISC_NOTSUP, PCAP_ERROR_NO_SUCH_DEVICE, or PCAP_ERROR_PERM_DENIED is returned, pcap_geterr() or pcap_perror() may be called with p as an argument to fetch or display an message giving additional details about the problem that might be useful for debugging the problem if it's unexpected.

顺便说一下,您还应该检查 pcap_create() return 是否为 NULL。