没有得到理想的输出

时间:2011-05-12 13:25:29

标签: ipv6

extern "C" int RTinet_lookup( const char * host,RTinet_address *address,RTinet_port port)
{
  struct addrinfo,*res;
  int errcode;
  char addrstr[INET6_ADDRSTRLEN];


  memset (&hints, 0, sizeof (hints));
  hints.ai_family = AF_UNSPEC;  
  hints.ai_socktype = SOCK_STREAM;
  hints.ai_protocol = IPPROTO_TCP;
  hints.ai_flags |= AI_CANONNAME;

  errcode = getaddrinfo (host, NULL , &hints, &res);
  if (errcode != 0)
    {
      INFO("getaddrinfo");
      return -1;
    }
  INFO(STR("Host: %s", host));
  if(res == NULL)
  {
    INFO(STR("NULL VALUE OF RES"));
  }
  else
  {INFO(STR("IN ELSE PART"));
  while (res)
    {
      INFO(STR("Inside while condition with res "));
      switch (res->ai_family)
        {
        case AF_INET:
          inet_ntop(AF_INET, &((struct sockaddr_in *) res->ai_addr)->sin_addr,addrstr, INET_ADDRSTRLEN);
          break;
        case AF_INET6:
          inet_ntop(AF_INET6, &((struct sockaddr_in6 *) res->ai_addr)->sin6_addr ,addrstr, INET6_ADDRSTRLEN);
          break;
        }
      res = res->ai_next;
    }
   }
   INFO(STR("IPv%d address: %s ", res->ai_family == AF_INET6 ? 6 : 4, addrstr));
   return 1;
}

这里我传递"::1"作为主机地址,这是一个IPV6表单。但是我正在追踪

Host: ::1    
IPv4 address: ::1

为什么选择IPv4 ???应该使用IPv6,因为在这种情况下地址族应该是AF_INET6

1 个答案:

答案 0 :(得分:1)

res指向NULL,因此您的上一个print语句无效,因为您认为ai_family != AF_INET6必须为AF_INET

编辑:为了进一步解释,这里是你的代码问题,删除了不相关的点:

while (res)
{
  res = res->ai_next;
}
INFO(STR("IPv%d address: %s ", res->ai_family == AF_INET6 ? 6 : 4, addrstr));

res循环结束时,问问自己while的价值是什么。