kap*_*aps 5 c++ sockets network-programming getaddrinfo
我面临的问题是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;
}
Run Code Online (Sandbox Code Playgroud)
输出:
IP v4 - xx.xx.xx.xx
Run Code Online (Sandbox Code Playgroud)
由于我已经设置hints.ai_family = AF_UNSPEC,它应该返回我的细节(ipv4和ipv6).但它只返回ipv4的细节.
注意:在命令中ifconfig我可以看到两者ipv4和ipv6地址.
> $ 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
Run Code Online (Sandbox Code Playgroud)
可以onyone解释我为什么不选择ipv6?
我是否需要在主机(Linux)上进行任何更改?
我删除了实际的ip详细信息并替换为xxxx.