IPv6 Address as text (C)

Ken Moore ken at pcbsd.org
Wed Dec 9 14:11:47 UTC 2015


Note: Please CC me on replies - I am not subscribed to this list.

I am having a bit of trouble getting an accurate string representation 
of the current IPv6 address for a given device using the C system 
libraries and was wondering of somebody with more experience than me 
might be able to spot the error...

Background:
I have been working on a couple simple C/C++/Qt functions to return 
printable forms of the current ipv4 and ipv6 addresses assigned to a 
particular device, and while the ipv4 function works fine the ipv6 
address is consistently wrong and almost always the same string - making 
me think it is converting some internal error code to a string 
("::XXe2:ffff:ff7f:0" where the "X"s are the only two characters which 
ever change).

The two functions are nearly identical, and I think the error probably 
comes from needing to use inet_ntop() for the ipv6 address because there 
is no ipv6-compatible version of the inet_ntoa() function.
Do you have any thoughts or ideas about where the error might be coming 
from or a better way to read off the ipv6 address as a string?

Here are the two functions:
Note: "name" is the QString of the device name (wlan0, re0, other...), 
and is an internal variable for the overall "NetDevice" class
[code]
//Fetch the IPv4 address and return it as a QString
QString NetDevice::ipAsString(){
    struct ifreq ifr;
    memset(&ifr, 0, sizeof(struct ifreq));

    strncpy(ifr.ifr_name, name.toLocal8Bit(), IFNAMSIZ);
    int s = socket(PF_INET, SOCK_DGRAM, 0);

    ioctl(s, SIOCGIFADDR, &ifr);
    struct in_addr in = ((sockaddr_in *) &ifr.ifr_addr)->sin_addr;

    return QString( inet_ntoa(in) );
}

//Fetch the IPv6 address and return it as a QString
QString NetDevice::ipv6AsString(){
    struct ifreq ifr;
    memset(&ifr, 0, sizeof(struct ifreq));

    strncpy(ifr.ifr_name, name.toLocal8Bit(), IFNAMSIZ);
    int s = socket(PF_INET6, SOCK_DGRAM, 0);

    ioctl(s, SIOCGIFADDR, &ifr);
    struct in6_addr in = ((sockaddr_in6 *) &ifr.ifr_addr)->sin6_addr;

    char straddr[INET6_ADDRSTRLEN];
      inet_ntop(AF_INET6, &in, straddr, sizeof(straddr));
      return QString( inet_ntop(AF_INET6, &in, straddr, sizeof(straddr)) );
}
[/code]

Thanks! Any input is appreciated!

-- 
~~ Ken Moore ~~
PC-BSD/iXsystems



More information about the freebsd-net mailing list