我正在尝试为ipv6编写客户端服务器程序。我在尝试调用getaddrinfo函数时遇到问题。返回-2(getaddrinfo:名称或服务未知)。
这在Windows系统上可以正常运行,但在Linux上则无法运行。
$ ifconfig |grep inet6
inet6 fe80::e41b:2c23:a286:77a prefixlen 64 scopeid 0x20<link>
inet6 ::1 prefixlen 128 scopeid 0x10<host>
ifconfig表示已启用ipv6。甚至我也可以从另一台主机ping此IP。
#include <iostream>
#include <string.h>
#include <netdb.h>
#include <arpa/inet.h>
int main(int argc, char** argv)
{
addrinfo hints = {}, *results, *res;
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_INET6;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
int m = getaddrinfo(argv[1], "2019", &hints, &results);
if (m < 0)
{
std::cout << "getaddrinfo : " << gai_strerror(m) << std::endl;
return 1;
}
for(res = results; res != NULL; res = res->ai_next)
{
char straddr[INET6_ADDRSTRLEN] = {};
if (inet_ntop(res->ai_family, &(reinterpret_cast<sockaddr_in6*>(res->ai_addr)->sin6_addr), straddr, sizeof(straddr)))
std::cout << "IP - " << straddr << "\n";
else
std::cout << "inet_ntop error";
}
freeaddrinfo(results);
return 0;
}
应该以v6格式打印ip,但是会打印 getaddrinfo:名称或服务未知