【问题标题】:How can I enumerate the list of network devices or interfaces in C or C++ in FreeBSD? [duplicate]如何在 FreeBSD 中枚举 C 或 C++ 中的网络设备或接口列表? [复制]
【发布时间】:2014-05-10 06:17:43
【问题描述】:

如何在 FreeBSD 中枚举 C 或 C++ 中的网络设备或接口列表?

我想要一个像“ue0”、“ath0”、“wlan0”这样的列表。

我一直在查看 ifconfig(1) 代码,但根本不清楚任务在哪里执行。

我很乐意接受答案、指向手册页的指针或指向 ifconfig 中相应行的链接。我可能只是错过了它。

【问题讨论】:

    标签: c api freebsd


    【解决方案1】:

    getifaddrs API 获取接口地址。 man getifaddrs

    您也可以使用ioctl 获取网络接口。

    代码:

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

    输出:

    lo: IP 127.0.0.1, BROADCAST 0.0.0.0
    eth0: IP 192.168.1.9, BROADCAST 192.168.1.255
    

    【讨论】:

    • 那是 Linux API 而不是 FreeBSD API。顺便说一句,恰好有一个同名的 FreeBSD。感谢您的指点。修正你的答案,我会 +1 ;)
    • x.c:46:23: error: use of undeclared identifier 'SIOCGIFHWADDR' -- 确保不使用 Linux 细节
    • 你试过使用getifaddrs吗?我认为它也可以在FreeBSD 中找到。 freebsd.org/cgi/man.cgi?query=getifaddrs
    猜你喜欢
    • 1970-01-01
    • 2011-11-29
    • 1970-01-01
    • 2011-07-09
    • 1970-01-01
    • 1970-01-01
    • 2014-12-20
    • 1970-01-01
    • 2013-01-29
    相关资源
    最近更新 更多