How to check the status of network devices in C?

I would like to check the status of network devices, for example. impenetrable mode. Basically, as shown by the ip a command .

Can someone push me in the right direction?

I want to do this in C for linux, so specific linux headers are available.

+3
source share
1 answer

You need to use SIOCGIFFLAGSioctl to retrieve flags related to the interface. Then you can check if the flag is set 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;
}

, , , ifr_flags SIOCSIFFLAGS IOCTL:

/* ... */
ethreq.ifr_flags |= IFF_PROMISC;
ioctl(fd, SIOCSIFFLAGS, &ethreq);
+6

Source: https://habr.com/ru/post/1750342/


All Articles