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, 0, sizeof(hints)); hints.ai_flags = 0; hints.ai_family = PF_UNSPEC; hints.ai_socktype = SOCK_STREAM; int n = 0; if((n=getaddrinfo(ip_v4.c_str(), "http", &hints, &res0))!=0) { printf("getaddrinfo error: %s\n",gai_strerror(n)); return false; } struct sockaddr_in6* addr6; struct sockaddr_in* addr; char ipbuf[32] = {‘\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[4] = {192, 168, 2, 119}; char ipv4_str_buf[INET_ADDRSTRLEN] = { 0 }; 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);
原文:http://www.cnblogs.com/afan/p/6192514.html