I am testing IPv6 in Mac OS X 10.11.2 and I find a strange problem.
I use getaddrinfo to resolve hostname to IPv6 addr :
#include <stdio.h>
#include <netdb.h>
#include <errno.h>
#include <string.h>
#include <arpa/inet.h>
int main(int argc, const char * argv[]) {
struct addrinfo * res, * addr;
struct addrinfo hints;
char buffer[128];
struct sockaddr_in6 * sockaddr_v6;
memset(&hints, 0, sizeof(hints));
hints.ai_family = PF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_DEFAULT;
if (getaddrinfo("www.google.com", "80", &hints, &res)) {
//if (getaddrinfo("216.58.199.4", "80", &hints, &res)) {
printf("getaddrinfo failed with errno(-%d)\n", errno);
return 0;
}
for (addr = res;addr;addr = addr->ai_next)
{
if (addr->ai_family == AF_INET6)
{
sockaddr_v6 = (struct sockaddr_in6 *)addr->ai_addr;
printf("ipv6 addr is %s %d)\n", inet_ntop(AF_INET6, &sockaddr_v6->sin6_addr, buffer, sizeof(buffer)), ntohs(sockaddr_v6->sin6_port));
}
}
freeaddrinfo(res);
return 0;
}
output is
"ipv6 addr is 64:ff9b::d83a:c704 80". everything is ok !
"www.google.com" is resolved to "64:ff9b::d83a:c704", sin6_port is 80.
but when I use "216.58.199.4"
instead of "www.google.com"
, "216.58.199.4"
is IPv4
addr of "www.google.com"
.
//if (getaddrinfo("www.google.com", "80", &hints, &res)) {
if (getaddrinfo("216.58.199.4", "80", &hints, &res)) {
output is "ipv6 addr is 64:ff9b::d83a:c704 0"
. it is ok that "216.58.199.4"
is converted to "64:ff9b::d83a:c704"
, but it is strange that the service port of 80 become 0
.
Is anyone can explain it ?