2017-10-19 5 views
0

に戻って変換する:バイトコード化のPython 3にIPアドレスを、私のようなのpython3のサンプルUDPパケットヘッダーを作成しようとしている文字列

# "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 

私が欲しいのは、2行目の値です。

192.168.1.1 

どこが間違っているのですか?

+0

[IPアドレスをPythonのバイトに変換する]の可能な複製(https://stackoverflow.com/questions/33244775/converting-ip-address-into-bytes-in-python) – thatrockbottomprogrammer

+0

@thatrockbottomprogrammer私が苦労していることwithは文字列に戻ってipを変換しています – sgrew

答えて

0

ip_arg文字列をintに変換しないでください.19216811は、エンコードするintではありません。 192.168.1.1 = 3232235777をintとして返します。あなたは、デコードセクションでやっていることの逆を行い、各オクテットを変換することができます。

+0

SOLVED。デコードforループのバイトからintへの変換は、int.from_bytes([i]、 'big')でなければなりません。 – sgrew

関連する問題