Search code examples
clinuxopenwrt

Getting IP version 6 using C


I am able to get the IPv4 address of a given interface with following code

int fd;
char ipv4[33];
char ifname[] = "eth0";
struct ifreq ifr;

fd = socket(AF_INET, SOCK_DGRAM, 0);
ifr.ifr_addr.sa_family = AF_INET;
strncpy(ifr.ifr_name, ifname, IFNAMSIZ-1);
ioctl(fd, SIOCGIFADDR, &ifr);
close(fd);

snprintf(ipv4, 33, "%s", inet_ntoa(((struct sockaddr_in *)&ifr.ifr_addr)->sin_addr));

What is the easiest way to get the IPv6 address of a given interface, using C ?

*** I AM POSTING THE CODE WHICH I COULD USE TO MAKE IT BELOW ..

int8_t find_device_ipv6(const char *ifname, char *ipv6, int8_t ipv6_size)
{
    FILE *f;
    int ret, scope, prefix;
    unsigned char _ipv6[16];
    char dname[IFNAMSIZ];
    char address[INET6_ADDRSTRLEN];
    char *scopestr;

    f = fopen("/proc/net/if_inet6", "r");
    if (f == NULL) {
        return -1;
    }
    while (19 == fscanf(f,
                        " %2hhx%2hhx%2hhx%2hhx%2hhx%2hhx%2hhx%2hhx%2hhx%2hhx%2hhx%2hhx%2hhx%2hhx%2hhx%2hhx %*x %x %x %*x %s",
                        &_ipv6[0],
                        &_ipv6[1],
                        &_ipv6[2],
                        &_ipv6[3],
                        &_ipv6[4],
                        &_ipv6[5],
                        &_ipv6[6],
                        &_ipv6[7],
                        &_ipv6[8],
                        &_ipv6[9],
                        &_ipv6[10],
                        &_ipv6[11],
                        &_ipv6[12],
                        &_ipv6[13],
                        &_ipv6[14],
                        &_ipv6[15],
                        &prefix,
                        &scope,
                        dname)) {
        if (strcmp(ifname, dname) != 0) {
            continue;
        }
        if (inet_ntop(AF_INET6, _ipv6, address, sizeof(address)) == NULL) {
            continue;
        }
        snprintf(ipv6, ipv6_size, "%s", address);
    }
    fclose(f);

    return 0;
}

Solution

  • I assume your OS is Linux.

    To find out how it is done, try strace ifconfig eth0.

    You see that it is using /proc/net/if_inet6 and some ioctl, notably SIOCGIFADDR

    As Ctx commented, you probably want getifaddrs(3)