在Python中将IPv4地址转换为十六进制IPv6地址

时间:2013-11-03 07:52:47

标签: python hex type-conversion ip-address 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)

编辑:管理将IP地址转换为十六进制值。现在我该如何将此十六进制值转换为IPv6地址?

3 个答案:

答案 0 :(得分:3)

>>> ip_address = '123.45.67.89'
>>> numbers = list(map(int, ip_address.split('.')))
>>> '2002:{:02x}{:02x}:{:02x}{:02x}::'.format(*numbers)
'2002:7b2d:4359::'

答案 1 :(得分:2)

在Python 3.3中,您可以使用ipaddress module来操作IPv4,IPv6地址:

#!/usr/bin/env python3
import ipaddress

# get ip address 
while True:
    ip4str = input("Enter IPv4 (e.g., 9.254.253.252):")
    try:
        ip4 = ipaddress.IPv4Address(ip4str)
    except ValueError:
        print("invalid ip address. Try, again")
    else:
        break # got ip address

# convert ip4 to rfc 3056 IPv6 6to4 address
# http://tools.ietf.org/html/rfc3056#section-2
prefix6to4 = int(ipaddress.IPv6Address("2002::"))
ip6 = ipaddress.IPv6Address(prefix6to4 | (int(ip4) << 80))
print(ip6)
assert ip6.sixtofour == ip4

# convert ip4 to a base 10
print(int(ip4))
# convert ip4 to binary (0b)
print(bin(int(ip4)))
# convert ip4 to hex (0x)
print(hex(int(ip4)))

答案 2 :(得分:0)

在参考解决方案之前,先看一下this文档,了解ipv6表示的转换和约定。

def convert2bin(n, end='\n'):
    if n > 1:
        convert2bin(n//2, end='')
    print(n%2, end=end)