判断是否IPv6网络
Posted 啊饭
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了判断是否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, 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);
以上是关于判断是否IPv6网络的主要内容,如果未能解决你的问题,请参考以下文章
Twitter Kit RestAPI不支持IPv6? - 拒绝了Apple