测试ipv6情况

#coding=utf8


#ipv4环境下:
#getaddrinfo from: ipv6-test.com
#[(2, 2, 17, '', ('5.135.165.173', 0)), (2, 1, 6, '', ('5.135.165.173', 0)), (30, 2, 17, '', ('2001:41d0:8:e8ad::1', 0, 0, 0)), (30, 1, 6, '', ('2001:41d0:8:e8ad::1', 0, 0, 0))]
#INET,5.135.165.173
#INET6,2001:41d0:8:e8ad::1


#ipv6环境下
#getaddrinfo from: ipv6-test.com
#[(30, 2, 17, '', ('64:ff9b::587:a5ad', 0, 0, 0)), (30, 1, 6, '', ('64:ff9b::587:a5ad', 0, 0, 0)), (2, 2, 17, '', ('5.135.165.173', 0)), (2, 1, 6, '', ('5.135.165.173', 0))]
#INET6,64:ff9b::587:a5ad
#INET,5.135.165.173


#测试时发现只要环境是ipv6,测试总会返回两个地址,如果是ipv4则大部分只返回ipv4地址,除了特别配置了ipv6的服务会返回ipv6地址




import sys, socket


strHost = "ipv6-test.com"


print("getaddrinfo from: " + strHost)
result = socket.getaddrinfo(strHost, None)
print(result)
for r in result:
    if r[2] != socket.IPPROTO_TCP:
        continue
    if r[0] == socket.AF_INET:
        print("INET," + r[4][0])
    elif r[0] == socket.AF_INET6:
        print("INET6," + r[4][0])


#测试中看起来ipv4则第一个地址是ipv4地址,ipv6环境则第一个地址是ipv6地址,不论是否服务端真正支持ipv6
bEnvIPv6 = False
if len(result) > 0:
    if result[0][0] == socket.AF_INET6:
        bEnvIPv6 = True
if bEnvIPv6:
    print("IPv6 env.\n")
else:
    print("IPv4 env.\n")





你可能感兴趣的:(程序开发)