简体   繁体   English

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

[英]Converting IPv4 Address to a Hex IPv6 Address in Python

Q: Write a program that prompts the user for an IP address then converts this to a base 10, binary and hex value.问:编写一个程序,提示用户输入 IP 地址,然后将其转换为以 10 为基数的二进制和十六进制值。 The program then converts the hex value to an RFC3056 IPv6 6to4 address.然后程序将十六进制值转换为 RFC3056 IPv6 6to4 地址。

I have the base 10 and binary parts working but I can't seem to get my head around the hex part.我有基本的 10 和二进制部分工作,但我似乎无法理解十六进制部分。 Can the format string method be used somehow to accomplish the same thing?可以以某种方式使用格式字符串方法来完成同样的事情吗? Or would I need to import the ipaddress module in this case?或者在这种情况下我需要导入 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)

EDIT: Managed to convert the IP Address to hex value.编辑:管理将 IP 地址转换为十六进制值。 Now how do I convert this hex value into IPv6 address?现在如何将此十六进制值转换为 IPv6 地址?

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

In Python 3.3 you could use ipaddress module to manipulate IPv4, IPv6 addresses:在 Python 3.3 中,您可以使用ipaddress模块来操作 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)))

If you just want to use the IPv4 addresses in an IPv6 context (eg by passing to socket.connect() created using the socket.AF_INET6 address family), you can just use the syntax described in RFC4291, Section 2.2 :如果您只想在 IPv6 上下文中使用 IPv4 地址(例如通过传递给使用socket.AF_INET6地址族创建的socket.connect() ),您可以使用RFC4291 第 2.2 节中描述的语法:

>>> import socket
>>> a = '10.20.30.40'
>>> s = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM)
>>> s.connect(('2002::' + a, 9))

Ie just prepend ::ffff: to the IPv4 address and you get a valid 6to4 address.即,只需在 IPv4 地址前加上::ffff:即可获得有效的 6to4 地址。 If you instead want to convert this address to the more common hexadecimal form, I suggest using the standard library ipaddress module you mentioned:如果您想将此地址转换为更常见的十六进制形式,我建议使用您提到的标准库ipaddress模块:

>>> import ipaddress
>>> a = '10.20.30.40'
>>> print(ipaddress.IPv6Address('2002::' + a).compressed)
'2002::a14:1e28'

Before referring to the solution, have a look at this doc for conversion and convention of ipv6 representation.在参考解决方案之前,请查看文档以了解 ipv6 表示的转换和约定。

def ipconversion4to6(ipv4_address):
    hex_number = ["{:02x}".format(int(_)) for _ in address.split(".")]
    ipv4 = "".join(hex_number)
    ipv6 = "2002:"+ipv4[:4]+":"+ipv4[4:]+"::"
    return ipv6

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM