将IP地址转换为整数,反之亦然
为此,我们将使用 ipaddress 模块。 ipaddress 是一个帮助创建、操作和操作 IPv4 和 IPv6 地址和网络的模块。
将 IP 地址转换为整数(反之亦然)的动机是其他使用 IP 地址的模块(例如套接字)通常不会直接接受来自 ipaddress 模块的对象。相反,它们必须转换为字符串或其他模块将接受的整数。
Syntax: ipaddress.ip_address(address)
Parameter: Passing IP address in form of integer or string. Integers value less than 2**32 are considered as IPv4 addresses.
Returns: IPv4Address or IPv6Address object is returned depending on the IP address passed as argument. If address passed does not represent a valid IPv4 or IPv6 address, a ValueError is raised.
将整数转换为 IP 地址的程序:
Python3
# importing the module
import ipaddress
# converting int to IPv4 address
print(ipaddress.ip_address(3221225000))
print(ipaddress.ip_address(123))
# converting int to IPv6 address
print(ipaddress.ip_address(42540766400282592856903984001653826561))
Python3
# importing the module
import ipaddress
# converting IPv4 address to int
addr1 = ipaddress.ip_address('191.255.254.40')
addr2 = ipaddress.ip_address('0.0.0.123')
print(int(addr1))
print(int(addr2))
# converting IPv6 address to int
addr3 = ipaddress.ip_address('2001:db7:dc75:365:220a:7c84:d796:6401')
print(int(addr3))
输出:
191.255.254.40
0.0.0.123
2001:db7:dc75:365:220a:7c84:d796:6401
将 IP 地址转换为整数:
蟒蛇3
# importing the module
import ipaddress
# converting IPv4 address to int
addr1 = ipaddress.ip_address('191.255.254.40')
addr2 = ipaddress.ip_address('0.0.0.123')
print(int(addr1))
print(int(addr2))
# converting IPv6 address to int
addr3 = ipaddress.ip_address('2001:db7:dc75:365:220a:7c84:d796:6401')
print(int(addr3))
输出:
3221225000
123
42540766400282592856903984001653826561