How can I list the list of network devices or interfaces in C or C ++ in FreeBSD?

How can I list the list of network devices or interfaces in C or C ++ in FreeBSD?

I need a list like "ue0", "ath0", "wlan0".

I searched for ifconfig (1) code, but its not clear where this task is performed.

I will be happy to answer, a pointer to the manual page or a link to the corresponding line in ifconfig. Maybe I just missed it.

+4
source share
1 answer

getifaddrsThe API receives the interface addresses. man getifaddrs

You can also use ioctlto get network interfaces.

the code:

#include <sys/ioctl.h>
#include <net/if.h>
#include <netinet/in.h>
#include <stdio.h>
#include <arpa/inet.h>

int main(void)
{
    char          buf[1024];
    struct ifconf ifc;
    struct ifreq *ifr;
    int           sck;
    int           nInterfaces;
    int           i;

/* Get a socket handle. */
    sck = socket(AF_INET, SOCK_DGRAM, 0);
    if(sck < 0)
    {
        perror("socket");
        return 1;
    }

/* Query available interfaces. */
    ifc.ifc_len = sizeof(buf);
    ifc.ifc_buf = buf;
    if(ioctl(sck, SIOCGIFCONF, &ifc) < 0)
    {
        perror("ioctl(SIOCGIFCONF)");
        return 1;
    }

/* Iterate through the list of interfaces. */
    ifr         = ifc.ifc_req;
    nInterfaces = ifc.ifc_len / sizeof(struct ifreq);
    for(i = 0; i < nInterfaces; i++)
    {
        struct ifreq *item = &ifr[i];

    /* Show the device name and IP address */
        printf("%s: IP %s",
               item->ifr_name,
               inet_ntoa(((struct sockaddr_in *)&item->ifr_addr)->sin_addr));


    /* Get the broadcast address (added by Eric) */
        if(ioctl(sck, SIOCGIFBRDADDR, item) >= 0)
            printf(", BROADCAST %s", inet_ntoa(((struct sockaddr_in *)&item->ifr_broadaddr)->sin_addr));
        printf("\n");
    }

        return 0;
}

Conclusion:

lo: IP 127.0.0.1, BROADCAST 0.0.0.0
eth0: IP 192.168.1.9, BROADCAST 192.168.1.255
+4
source

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


All Articles