howto check a network devices status in C?

前端 未结 1 2038
萌比男神i
萌比男神i 2021-01-14 09:12

I would like to check a network devices status e.g. promiscous mode. Basically like shown with ip a command.

Maybe someone could push me in the righ

相关标签:
1条回答
  • 2021-01-14 09:34

    You need to use the SIOCGIFFLAGS ioctl to retrieve the flags associated with an interface. You can then check if the IFF_PROMISC flag is set:

    #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;
    }
    

    If you want to set the interface to promiscuous mode, you will need root privileges, but you can simply set the field in ifr_flags and use the SIOCSIFFLAGS ioctl:

    /* ... */
    ethreq.ifr_flags |= IFF_PROMISC;
    ioctl(fd, SIOCSIFFLAGS, &ethreq);
    
    0 讨论(0)
提交回复
热议问题