CocoaAsyncSocket(GCDAsyncSocket)如何支持IPv6

设置IPv4PreferredOverIPv6 属性为NO即可。
就这么简单:)
得到@郭秀才的提示.
如果你还是想用IP地址作为Host发起连接的话, 还需要做一个地方的修改

+ (NSMutableArray *)lookupHost:(NSString *)host port:(uint16_t)port error:(NSError **)errPtr {
    //....
                for (res = res0; res; res = res->ai_next)
            {
                if (res->ai_family == AF_INET)
                {
                    // Found IPv4 address.
                    // Wrap the native address structure, and add to results.

                    if (((struct sockaddr_in *)res->ai_addr)->sin_port == 0)
                        ((struct sockaddr_in *)res->ai_addr)->sin_port = htons(port);

                    NSData *address4 = [NSData dataWithBytes:res->ai_addr length:res->ai_addrlen];
                    [addresses addObject:address4];
                }
                else if (res->ai_family == AF_INET6)
                {
                    // Found IPv6 address.
                    // Wrap the native address structure, and add to results.

                    // 此处修改的合理性, 有待考察, Apple建议对IPv6-Only的支持方式是取消使用IP地址, 全部改用域名的方式
                    // 域名方式下, sin_port是有正确的值的. 
                    // 另外, IPv6 是否允许路由器变更端口, 这个也有待考察, 如果允许路由器变更端口, 那么这段代码的处理就有BUG了
                    if (((struct sockaddr_in6 *)res->ai_addr)->sin6_port == 0)
                        ((struct sockaddr_in6 *)res->ai_addr)->sin6_port = htons(port);
                    
                    NSData *address6 = [NSData dataWithBytes:res->ai_addr length:res->ai_addrlen];
                    [addresses addObject:address6];
                }
            }
    //....
}

相关的修改已经提交到了这里

你可能感兴趣的:(CocoaAsyncSocket(GCDAsyncSocket)如何支持IPv6)