Reputation: 39
I have an addrinfo structure that I get by calling the getaddrinfo()
function with the following parameters:
getaddrinfo(address, NULL, &hints, &res)
I need to store the IPv6 address in binary form and print it in hexadecimal form.
My question is, how do I store the IPv6 address in a character array of 16 elements?
Upvotes: 1
Views: 1233
Reputation: 13786
If getaddrinfo call was successful, then res contains a linked list of available struct addrinfo, in which you can obtain the ipaddress with its ai_addr member. If ai_family is AF_INET6, then you can copy the ipv6 address by following:
include <netinet/in.h>
unsigned char buf[INET_ADDRSTRLEN];
struct sockaddr_in6 *in6 = (struct sockaddr_in6*)addr->ai_addr;
memcpy(buf, in6->sin6_addr.s6_addr, 16);
To dump the bytes of the address:
for (int i = 0; i < 16; i++) {
printf("%02X", buf[i]);
if (i < 15) putchar(':');
}
To print the ipv6 address in canonical way, use inet_ntop:
char str[64];
printf("%s\n", inet_ntop(AF_INET6, buf, str, sizeof buf));
Upvotes: 5
Reputation: 851
After memcpy ing the address to a buffer, you could do this for hex output.
unsigned char buf[16];
memcpy(&buf, &addr, 16);`
printf("0x");
int i;
for(i = 0; i < 16; i++)
{
if(i && i % 2 == 0)
printf (":");
printf("%02x", buf[i]);
}
Upvotes: 0