2

So this is very simple, but I'm having trouble getting this to work. I want to, for example, if the incoming IP address string is '168.108.114.22', convert this to a bytes object like:

\xA8\x6C\x72\x16

Basically each part of the IP address is converted to it's hexadecimal equivalent.

I've tried so many ways but couldn't get what I want. String manipulation, using socket.inet_aton, packing, etc. I want to be able to send these bytes over a socket and then receive and parse them at the other end, but I am having trouble just getting my bytes object created and looking like that.

2 Answers 2

4

Python's inet_aton function should do what you need, it does return a string containing exactly 4 bytes:

import socket

print socket.inet_aton('168.108.114.22')
print socket.inet_aton('65.66.67.68')

These would display:

¨lr
ABCD 

And to convert the four characters back again using inet_ntoa:

print socket.inet_ntoa('\xA8\x6C\x72\x16')
print socket.inet_ntoa('ABCD')

Giving:

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

2 Comments

How would I convert this back to the IP address on the other end of the socket? If I sent it through this way, after converting using inet_aton.
ntoa i.e. network-to-ascii (they all come from good ol' C)
1

this

ip='168.108.114.22'

b_out = bytes(map(int,ip.split('.')))
print(b_out)

on python 3 produces

b'\xa8lr\x16'

which should be what you are looking for, if I understand correctly.

Note: there are more specific and optimized utility functions to manipulate IP addresses

Comments

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.