2017-10-19 6 views
0

로 다시 변환 :바이트 인코딩 파이썬 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 

내가 원하는 것은 두 번째 줄을위한 것입니다 :

192.168.1.1 

누구나 내가 어디로 잘못 가고 있는지 알 수 있습니까?

+0

[파이썬에서 IP 주소를 바이트로 변환] 가능한 복제본 (https://stackoverflow.com/questions/33244775/converting-ip-address-into-bytes-in-python) – thatrockbottomprogrammer

+0

@thatrockbottomprogrammer 내가 고심하는 것 와 함께 ip 백을 – sgrew

답변

0

ip_arg 문자열을 int로 변환하지 마십시오. 19216811은 인코딩하려는 int가 아닙니다. 192.168.1.1 = 3232235777을 int로 사용하십시오. 당신은 디코드 섹션에서하고있는 것과 반대로 할 수 있고 각 옥텟을 변환 할 수 있습니다.

+0

SOLVED 문자열로 변환 중입니다. int for_bytes ([i], 'big') : for 루프를 디코딩 할 때 int에서 byte로 변환해야합니다. – sgrew