0

I'm trying to create sample UDP packet headers in Python3 as such:

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

And the output is:

bytearray(b'\xc0\xa8\x01\x01\x15\xb3')

bytearray(b'\xc0\xa8\x01\x01')
0.0.168.168

What I want is for the second line to be:

192.168.1.1

Anyone know where I'm going wrong?

2
  • Possible duplicate of Converting IP address into bytes in python Commented Oct 19, 2017 at 5:51
  • @thatrockbottomprogrammer What I'm struggling with is converting the ip BACK to a string Commented Oct 19, 2017 at 6:15

1 Answer 1

1

Don't convert the ip_arg string to an int, 19216811 is not the int you want to encode. 192.168.1.1 = 3232235777 as an int. You could do the reverse of what you're doing in the decode section and convert each octet.

Sign up to request clarification or add additional context in comments.

1 Comment

SOLVED. The byte to int conversion in the decoding for loop should be: int.from_bytes([i], 'big')

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.