转自:https://www.jianshu.com/p/9926b99a7fef
以前cocos2d-x的项目里都使用的是libwebsocket,如果想支持ipv6,只需要升级相应的库即可,现在有个项目里使用的是原生socket,如果要支持ipv6可能需要进行一些代码的改造,具体可参考如下代码:
struct addrinfo *result; struct addrinfo *res; struct addrinfo addrCriteria; memset(&addrCriteria,0,sizeof(addrCriteria)); addrCriteria.ai_family=AF_UNSPEC; addrCriteria.ai_socktype=SOCK_STREAM; addrCriteria.ai_protocol=IPPROTO_TCP; //判定网络类型 指定特定接口信息 int error = getaddrinfo("www.baidu.com", "1100", &addrCriteria, &result); if (error == 0) { struct sockaddr_in *sa; for (res = result; res != NULL; res = res->ai_next) { if (AF_INET6 == res->ai_addr->sa_family) { char buf[128] = {}; sa = (struct sockaddr_in*)res->ai_addr; inet_ntop(AF_INET6, &((reinterpret_cast<struct sockaddr_in6*>(sa))->sin6_addr), buf, 128); m_sock = socket(res->ai_family, res->ai_socktype, 0); if (m_sock == -1) { log("error socket create"); return; } struct sockaddr_in6 svraddr; memset(&svraddr, 0, sizeof(svraddr)); //注意初始化 svraddr.sin6_family = AF_INET6; svraddr.sin6_port = htons(port); if (inet_pton(AF_INET6,buf,&svraddr.sin6_addr) < 0) { log("error addr"); } int ret = connect(m_sock, (struct sockaddr*) &svraddr, sizeof(svraddr)); //TODO....遇到IPv6就退出 break; } else if (AF_INET == res->ai_addr->sa_family) { char buf[32] = {}; sa = (struct sockaddr_in*)res->ai_addr; inet_ntop(AF_INET, &sa->sin_addr), buf, 32); m_sock = socket(res->ai_family, res->ai_socktype, 0); if (m_sock == -1) { log("error socket create"); return; } struct sockaddr_in svraddr; svraddr.sin_family = AF_INET; svraddr.sin_addr.s_addr = inet_addr(buf); svraddr.sin_port = htons(port); int ret = connect(m_sock, (struct sockaddr*) &svraddr, sizeof(svraddr)); //TODO.... break除掉 //break; } } }