如何从 inet_pton() 的输出中以点分二进制表示法在 f 字符串中打印 IP 地址?
How can I print in an f-string an IP address in the dotted binary notation from the output of inet_pton()?
以下代码is supposed to take an IP from its user, convert it to the binary并将其打印到屏幕上。
#!/usr/bin/env python3
from socket import inet_aton, inet_pton, AF_INET
ip = input("IP?\n")
ip = inet_pton(AF_INET, ip)
print(f"{ip}")
当给定 185.254.27.69
它打印
b'\xb9\xfe\x1bE'
.f"{ip:08b}"
does not work,可能是因为四个八位字节之间的三个点。我怎样才能在屏幕上打印 IP 的点分二进制格式?有什么资源可以用吗?
此代码适用于二进制 ip 并保持前导零:
from socket import inet_aton, inet_pton, AF_INET
ip = ip2 = input("IP?\n")
ip = inet_pton(AF_INET, ip)
ip2 = ip2.split(".")
ip3 = ""
for ip in ip2:
ip = int(ip)
if len(ip3) == 0:
zeros = str(bin(ip)[2:]).zfill(8)
ip3 += zeros
else:
zeros = str(bin(ip)[2:]).zfill(8)
ip3 += "." + zeros
print(f"{ip3}")
除非我遗漏了什么,否则我看不到在这里使用 inet_pton 的理由。当您需要数字的二进制表示时(我假设),它会转换为打包字节:
ip = input("IP?\n")
print('.'.join(f'{int(num):08b}' for num in ip.split('.')))
对于您提供的输入:
IP?
185.254.27.69
10111001.11111110.00011011.01000101
以下代码is supposed to take an IP from its user, convert it to the binary并将其打印到屏幕上。
#!/usr/bin/env python3
from socket import inet_aton, inet_pton, AF_INET
ip = input("IP?\n")
ip = inet_pton(AF_INET, ip)
print(f"{ip}")
当给定 185.254.27.69
它打印
b'\xb9\xfe\x1bE'
.f"{ip:08b}"
does not work,可能是因为四个八位字节之间的三个点。我怎样才能在屏幕上打印 IP 的点分二进制格式?有什么资源可以用吗?
此代码适用于二进制 ip 并保持前导零:
from socket import inet_aton, inet_pton, AF_INET
ip = ip2 = input("IP?\n")
ip = inet_pton(AF_INET, ip)
ip2 = ip2.split(".")
ip3 = ""
for ip in ip2:
ip = int(ip)
if len(ip3) == 0:
zeros = str(bin(ip)[2:]).zfill(8)
ip3 += zeros
else:
zeros = str(bin(ip)[2:]).zfill(8)
ip3 += "." + zeros
print(f"{ip3}")
除非我遗漏了什么,否则我看不到在这里使用 inet_pton 的理由。当您需要数字的二进制表示时(我假设),它会转换为打包字节:
ip = input("IP?\n")
print('.'.join(f'{int(num):08b}' for num in ip.split('.')))
对于您提供的输入:
IP?
185.254.27.69
10111001.11111110.00011011.01000101