python中IPv6与ipv4的相互转换(已测试)

首先吐槽下,网上大部分答案就知道复杂粘贴,都不能用…,也不测试一下
1.ipv6 转为 ipv4

import socket
ipv6_address = "2023:0db8:85a3:0000:0000:8a2e:0370:7334"
ip6_net = socket.inet_pton(socket.AF_INET6, ipv6_address)[-4:]
ip4 = socket.inet_ntoa(ip6_net)
print(ip4)  # 3.112.115.52
  1. ipv4 转为 ipv6
ipv4_address = '3.112.115.52'
ipv6 = ipaddress.IPv6Address('::ffff:' + ipv4_address)
hex_address = ipv6.exploded
print(hex_address)  # 0000:0000:0000:0000:0000:ffff:0370:7334

你可能感兴趣的:(python,开发语言)