簡體   English   中英

在 Python 中將 IPv4 地址轉換為十六進制 IPv6 地址

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

問:編寫一個程序,提示用戶輸入 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 地址?

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

在 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)))

如果您只想在 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))

即,只需在 IPv4 地址前加上::ffff:即可獲得有效的 6to4 地址。 如果您想將此地址轉換為更常見的十六進制形式,我建議使用您提到的標准庫ipaddress模塊:

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

在參考解決方案之前,請查看文檔以了解 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