how to get IPV6 interface address using getifaddr() function [duplicate]

本秂侑毒 提交于 2019-11-28 06:18:26

问题


This question already has an answer here:

  • How to know the IP address for interfaces in C using IPv6 1 answer

I have getifaddrs() definition but it is for IPv4. Please guide me how to get IPv6 if address using the getifaddrs() function.


回答1:


getifaddrs does support IPv6. Here's an example on how to print the name and IP address of all interfaces on the system:

struct ifaddrs *ifa, *ifa_tmp;
char addr[50];

if (getifaddrs(&ifa) == -1) {
    perror("getifaddrs failed");
    exit(1);
}

ifa_tmp = ifa;
while (ifa_tmp) {
    if ((ifa_tmp->ifa_addr) && ((ifa_tmp->ifa_addr->sa_family == AF_INET) ||
                              (ifa_tmp->ifa_addr->sa_family == AF_INET6))) {
        if (ifa_tmp->ifa_addr->sa_family == AF_INET) {
            // create IPv4 string
            struct sockaddr_in *in = (struct sockaddr_in*) ifa_tmp->ifa_addr;
            inet_ntop(AF_INET, &in->sin_addr, addr, sizeof(addr));
        } else { // AF_INET6
            // create IPv6 string
            struct sockaddr_in6 *in6 = (struct sockaddr_in6*) ifa_tmp->ifa_addr;
            inet_ntop(AF_INET6, &in6->sin6_addr, addr, sizeof(addr));
        }
        printf("name = %s\n", ifa_tmp->ifa_name);
        printf("addr = %s\n", addr);
    }
    ifa_tmp = ifa_tmp->ifa_next;
}


来源:https://stackoverflow.com/questions/33125710/how-to-get-ipv6-interface-address-using-getifaddr-function

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!