2017-10-19 123 views
0

我試圖創建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 

任何人都知道我要去哪裏錯了?

+0

可能重複的[在python中將IP地址轉換爲字節](https://stackoverflow.com/questions/33244775/converting-ip-address-into-bytes-in-python) – thatrockbottomprogrammer

+0

@thatrockbottomprogrammer我在掙扎與正在將IP BACK轉換爲字符串 – sgrew

回答

0

不要將ip_arg字符串轉換爲int,19216811不是要編碼的int。 192.168.1.1 = 3232235777作爲int。你可以在解碼部分做相反的操作,並轉換每個八位字節。

+0

解決。解碼循環中的字節到字符轉換應該是:int.from_bytes([i],'big') – sgrew

相關問題