在Python中将IPv4地址转换为十六进制IPv6地址 [英] Converting IPv4 Address to a Hex IPv6 Address in Python

查看:442
本文介绍了在Python中将IPv4地址转换为十六进制IPv6地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Q:编写一个程序,提示用户输入IP地址,然后将其转换为以10为底的二进制和十六进制值.然后,程序将十六进制值转换为RFC3056 IPv6 6to4地址.

Q: Write a program that prompts the user for an IP address then converts this to a base 10, binary and hex value. The program then converts the hex value to an RFC3056 IPv6 6to4 address.

我有以10为底的部分和二进制部分,但似乎无法绕过六角部分.可以使用格式字符串方法以某种方式完成同一件事吗?还是在这种情况下需要导入ipaddress模块​​?

I have the base 10 and binary parts working but I can't seem to get my head around the hex part. 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?

#!/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地址?

Managed to convert the IP Address to hex value. Now how do I convert this hex value into IPv6 address?

推荐答案

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

这篇关于在Python中将IPv4地址转换为十六进制IPv6地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆