如何检查C中的网络设备状态?

mat*_*ull 3 c linux networking device

我想检查网络设备状态,例如promiscous模式.基本上就像用ip命令一样.

也许有人可以把我推向正确的方向?

我想在C for linux中执行此操作,因此可以使用特定于Linux的标头.

Joh*_*ter 6

您需要使用SIOCGIFFLAGSioctl来检索与接口关联的标志.然后,您可以检查是否IFF_PROMISC设置了标志:

#include <stdlib.h>
#include <stdio.h>
#include <string.h>     
#include <sys/ioctl.h>  /* ioctl()  */
#include <sys/socket.h> /* socket() */
#include <arpa/inet.h>  
#include <unistd.h>     /* close()  */
#include <linux/if.h>   /* struct ifreq */

int main(int argc, char* argv[])
{
    /* this socket doesn't really matter, we just need a descriptor 
     * to perform the ioctl on */
    int fd = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);

    struct ifreq ethreq;

    memset(&ethreq, 0, sizeof(ethreq));

    /* set the name of the interface we wish to check */
    strncpy(ethreq.ifr_name, "eth0", IFNAMSIZ);
    /* grab flags associated with this interface */
    ioctl(fd, SIOCGIFFLAGS, &ethreq);
    if (ethreq.ifr_flags & IFF_PROMISC) {
        printf("%s is in promiscuous mode\n",
               ethreq.ifr_name);
    } else {
        printf("%s is NOT in promiscuous mode\n",
               ethreq.ifr_name);
    }

    close(fd);

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

如果要将接口设置为混杂模式,则需要root权限,但您只需设置字段ifr_flags并使用SIOCSIFFLAGSioctl:

/* ... */
ethreq.ifr_flags |= IFF_PROMISC;
ioctl(fd, SIOCSIFFLAGS, &ethreq);
Run Code Online (Sandbox Code Playgroud)