Linux获取所有网口及其详细信息

获取方法:

调用getifaddrs接口来获取,调用freeifaddrs接口来释放内存

需包含:

#include 
#include 

参考代码:

#include 
#include 
#include 
#include 
#include 
#include 

int main(int argc, char* argv[])
{
        struct ifaddrs *ifaddr_lst;
        struct ifaddrs *ifaddr_node;
        int family;
        char host[NI_MAXHOST];

        if(getifaddrs(&ifaddr_lst) < 0)
        {
                perror("getifaddrs");
                return -1;
        }

        for(ifaddr_node = ifaddr_lst; ifaddr_node != NULL; ifaddr_node = ifaddr_node->ifa_next)
        {
                /* ifa_addr可能为空,*/
                if(NULL == ifaddr_node->ifa_addr)
                {
                        continue;
                }

                struct sockaddr_in *addr = (struct sockaddr_in*)ifaddr_node->ifa_addr;
                family = addr->sin_family;

                printf("----------------------------------------\n");
                printf("interface name: %s\n", ifaddr_node->ifa_name);
                printf("address family: %d(%s)\n", family, (family == AF_PACKET)?"AF_PACKET":
                                                (family == AF_INET)?"AF_INET":
                                                (family == AF_INET6)?"AF_INET6":"");
                if(family == AF_INET||family == AF_INET6)
                {
                        int ret = getnameinfo(ifaddr_node->ifa_addr, (family == AF_INET)?sizeof(struct sockaddr_in):sizeof(struct sockaddr_in6), host, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
                        if( ret != 0 )
                        {
                                printf("getnameinfo failed:%s\n", strerror(ret));
                                return -1;
                        }

                        printf("address: %s\n", host);
                }
                printf("----------------------------------------\n");

        }

        freeifaddrs(ifaddr_lst);
        return 0;
}


你可能感兴趣的:(Linux,网口,linux)