I am facing issues in getting ipv6
using getaddrinfo()
:
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <netdb.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <arpa/inet.h>
int main()
{
int soc = 00;
struct addrinfo hints,*results,*res;
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
hints.ai_flags = AI_PASSIVE;
int m = getaddrinfo("myhost","2018",&hints,&results);
if (m<0)
{
printf("getaddrinfo error : %s\n", gai_strerror(m));
return 1;
}
res=results;
do
{
if(res->ai_family == AF_INET6)
{
struct sockaddr_in6* a= (struct sockaddr_in6*)res->ai_addr;
char straddr[INET6_ADDRSTRLEN];
inet_ntop(AF_INET6, &a->sin6_addr, straddr, sizeof(straddr));
printf("IP v6 - %s\n",straddr);
}
if(res->ai_family == AF_INET)
{
struct sockaddr_in* b= (struct sockaddr_in*)res->ai_addr;
const char* dotted_decimal1 = inet_ntoa(b->sin_addr);
printf("IP v4 - %s\n",dotted_decimal1);
}
}
while((res=res->ai_next) !=NULL);
return 0;
}
Output:
IP v4 - xx.xx.xx.xx
Since I have set hints.ai_family = AF_UNSPEC
, it should return me both the details (ipv4
and ipv6
). But it is returning details of ipv4 only.
Note: on command ifconfig
I can see both ipv4
and ipv6
address.
> $ ifconfig
> eth3 Link encap:Ethernet HWaddr xx:xx:xx:xx:xx:xx
> inet addr:x.x.x.x Bcast:x.x.x.x Mask:255.255.255.128
> inet6 addr: xx::xx:xx:xx:xx/64 Scope:Link
Can onyone explain me why it is not picking ipv6?
Do I need to make any changes on my host (Linux)?
I have removed the actual ip details and replaced with xxxx.