IPv6 Address as text (C)
Ken Moore
ken at pcbsd.org
Wed Dec 9 17:26:19 UTC 2015
On 12/09/2015 11:51, Andrey V. Elsukov wrote:
> On 09.12.15 18:25, Ken Moore wrote:
>
> Simple example:
>
> #include <sys/cdefs.h>
> __FBSDID("$FreeBSD$");
>
> #include <sys/types.h>
> #include <sys/socket.h>
> #include <arpa/inet.h>
>
> #include <err.h>
> #include <ifaddrs.h>
> #include <netdb.h>
> #include <stdio.h>
> #include <string.h>
>
> int
> main(int argc, char **argv)
> {
> char buf[INET6_ADDRSTRLEN];
> struct ifaddrs *ifap, *ifa;
> int error;
>
> if (getifaddrs(&ifap) != 0)
> err(1, "getifaddrs");
> for (ifa = ifap; ifa; ifa = ifa->ifa_next)
> if (ifa->ifa_addr->sa_family == AF_INET6) {
> error = getnameinfo(ifa->ifa_addr,
> ifa->ifa_addr->sa_len, buf, sizeof(buf),
> NULL, 0, NI_NUMERICHOST);
> if (error != 0)
> err(1, "%s", gai_strerror(error));
> printf("%s\n", buf);
> }
> freeifaddrs(ifap);
> return (0);
> }
>
Thanks!
Using getifaddrs() to fetch the pre-existing socket address did the trick.
Here is the final form of the function which works (although I am sure I
can clean it up a bit still...):
[code]
QString NetDevice::ipv6AsString(){
//Get the sockaddr for the device
struct sockaddr *sadd = 0;
struct ifaddrs *addrs;
if( 0!=getifaddrs( &addrs ) ){ qDebug() << "Could not get addrs";
return ""; }
while(sadd==0 && addrs!=0){
if( QString(addrs->ifa_name)==name &&
addrs->ifa_addr->sa_family==AF_INET6){
//Found device (with IPv6 address)
sadd = addrs->ifa_addr;
break;
}else{
//Move to the next device
addrs = addrs->ifa_next;
}
}
free(addrs);
if(sadd==0){ qDebug() << "No socket address found"; return ""; }
//Now get the IPv6 address in string form
char straddr[INET6_ADDRSTRLEN];
int err = getnameinfo(sadd, sadd->sa_len, straddr,
sizeof(straddr),NULL, 0, NI_NUMERICHOST);
if(err!=0){
qDebug() << "getnameinfo error:" << gai_strerror(err);
return "";
}else{
return QString(straddr);
}
}
[/code]
Thanks everybody!
--
~~ Ken Moore ~~
PC-BSD/iXsystems
More information about the freebsd-net
mailing list