Date: Wed, 9 Dec 2015 12:26:16 -0500 From: Ken Moore <ken@pcbsd.org> To: "Andrey V. Elsukov" <bu7cher@yandex.ru>, Hiroki Sato <hrs@FreeBSD.org> Cc: freebsd-net@freebsd.org Subject: Re: IPv6 Address as text (C) Message-ID: <56686438.8000109@pcbsd.org> In-Reply-To: <56685C23.600@yandex.ru> References: <5668369F.9020309@pcbsd.org> <20151209.233515.1592617248580059512.hrs@allbsd.org> <566847F3.7060900@pcbsd.org> <56685C23.600@yandex.ru>
next in thread | previous in thread | raw e-mail | index | archive | help
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
Want to link to this message? Use this URL: <https://mail-archive.FreeBSD.org/cgi/mid.cgi?56686438.8000109>
