use*_*786 3 python hex ip-address type-conversion ipv6
问:编写一个程序,提示用户输入 IP 地址,然后将其转换为以 10 为基数的二进制和十六进制值。然后程序将十六进制值转换为 RFC3056 IPv6 6to4 地址。
我有基本的 10 和二进制部分工作,但我似乎无法理解十六进制部分。可以以某种方式使用格式字符串方法来完成同样的事情吗?或者在这种情况下我需要导入 ipaddress 模块吗?
#!/usr/bin/python3
ip_address = input("Please enter a dot decimal IP Address: ")
"""This part converts to base 10"""
ListA = ip_address.split(".")
ListA = list(map(int, ListA))
ListA = ListA[0]*(256**3) + ListA[1]*(256**2) + ListA[2]*(256**1) + ListA[3]
print("The IP Address in base 10 is: " , ListA)
"""This part converts to base 2"""
base2 = [format(int(x), '08b') for x in ip_address.split('.')]
print("The IP Address in base 2 is: ", base2)
"""This part converts to hex"""
hexIP = []
[hexIP.append(hex(int(x))[2:].zfill(2)) for x in ip_address.split('.')]
hexIP = "".join(hexIP)
print("The IP Address in hex is: " , hexIP)
Run Code Online (Sandbox Code Playgroud)
编辑:管理将 IP 地址转换为十六进制值。现在如何将此十六进制值转换为 IPv6 地址?
>>> ip_address = '123.45.67.89'
>>> numbers = list(map(int, ip_address.split('.')))
>>> '2002:{:02x}{:02x}:{:02x}{:02x}::'.format(*numbers)
'2002:7b2d:4359::'
Run Code Online (Sandbox Code Playgroud)