字节编码在Python 3的IP地址,并转换回字符串
问题描述:
我试图创建Python3样品UDP数据包报头这样:字节编码在Python 3的IP地址,并转换回字符串
# "encoding"
header = bytearray()
ip = '192.168.1.1'
ip_bytes = bytes(map(int, ip.split('.')))
header.extend(ip_bytes)
port = 5555
header.extend(port.to_bytes(2, 'big'))
print(header)
print()
# "decoding"
destip = header[:4]
ips = ""
for i in destip:
byt = int.from_bytes(destip[i:i+1], 'big')
ips += str(byt) + "."
ips = ips[:len(ips)-1]
print(ips)
,输出是:
bytearray(b'\xc0\xa8\x01\x01\x15\xb3')
bytearray(b'\xc0\xa8\x01\x01')
0.0.168.168
我想要的第二行是:
192.168.1.1
任何人都知道我要去哪里错了?
答
不要将ip_arg字符串转换为int,19216811不是要编码的int。 192.168.1.1 = 3232235777作为int。你可以在解码部分做相反的操作,并转换每个八位字节。
+0
解决。解码循环中的字节到字符转换应该是:int.from_bytes([i],'big') – sgrew
可能重复的[在python中将IP地址转换为字节](https://*.com/questions/33244775/converting-ip-address-into-bytes-in-python) – thatrockbottomprogrammer
@thatrockbottomprogrammer我在挣扎与正在将IP BACK转换为字符串 – sgrew