Converting IP address into bytes in python
11,049
Solution 1
Go with Maciej Gol's answer, but here's another way:
ip = '192.168.1.1'
ip_as_bytes = bytes(map(int, ip.split('.')))
EDIT: Oops, this is Python 3.X only. For Python 2.X
ip = '192.168.1.1'
ip_as_bytes = ''.join(map(chr,map(int,ip.split('.'))))
You're better off using the socket module, however, given its efficiency:
>>> timeit.timeit("socket.inet_aton('164.107.113.18')",setup='import socket')
0.22455310821533203
>>> timeit.timeit("''.join(map(chr,map(int,'164.107.113.18'.split('.'))))")
3.8679449558258057
Solution 2
Use socket.inet_aton
:
>>> import socket
>>> socket.inet_aton('164.107.113.18')
'\xa4kq\x12'
>>> socket.inet_aton('127.0.0.1')
'\x7f\x00\x00\x01'
This returns a byte-string (or bytes
object on Python 3.x) that you can get bytes from. Alternatively, you can use struct
to get each byte's integer value:
>>> import socket
>>> import struct
>>> struct.unpack('BBBB', socket.inet_aton('164.107.113.18'))
(164, 107, 113, 18)
Related videos on Youtube

Author by
user3261349
Updated on September 15, 2022Comments
-
user3261349 4 months
Say i have an IP address in python
addr = '164.107.113.18'
How do i convert the IP address into 4 bytes?
-
Andy about 7 yearsWhat is your expected result? You have an extra period in your IP.
-
-
user3261349 about 7 yearsSo does socket.inet_aton(addr) return a string of 4 characters?
-
Maciej Gol about 7 yearsFor Python 2.x a
str
object is just a byte string, thus these 4 characters represent 4 bytes. For 3.x it returns a bytes object.