简体   繁体   中英

Converting an IP Address string to exactly 4 bytes in Python

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM