判断是否IPv6网络

bool isIPV6Net(const std::string ip_v4, std::string& out_ip)
{
bool is_v6 = false; struct addrinfo* res0;
struct addrinfo hints;
struct addrinfo* res; memset(&hints, , sizeof(hints));
hints.ai_flags = ;
hints.ai_family = PF_UNSPEC;
hints.ai_socktype = SOCK_STREAM; int n = ;
if((n=getaddrinfo(ip_v4.c_str(), "http", &hints, &res0))!=)
{
printf("getaddrinfo error: %s\n",gai_strerror(n));
return false;
} struct sockaddr_in6* addr6;
struct sockaddr_in* addr;
char ipbuf[] = {'\0'}; for(res = res0; res; res = res->ai_next)
{
if(res->ai_family == AF_INET6)
{
addr6 =( struct sockaddr_in6*)res->ai_addr;
inet_ntop(AF_INET6, &addr6->sin6_addr, ipbuf, sizeof(ipbuf));
is_v6 = true;
}
else
{
addr =( struct sockaddr_in*)res->ai_addr;
inet_ntop(AF_INET, &addr->sin_addr, ipbuf, sizeof(ipbuf));
}
break;
}
out_ip = ipbuf;
return is_v6;
}

测试:

char ipv4[] = {, , , };
char ipv4_str_buf[INET_ADDRSTRLEN] = { };
const char *ipv4_str = inet_ntop(AF_INET, &ipv4, ipv4_str_buf, sizeof(ipv4_str_buf)); std::string out_ip;
bool is = isIPV6Net("64:ff9b::739f:62d", out_ip);
上一篇:Linux进程状态 ( Linux Process State Codes)


下一篇:iOS开发Xcode7真机调试教程