Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting IP address into bytes in python

Tags:

python

ip

Say i have an IP address in python

addr = '164.107.113.18'

How do i convert the IP address into 4 bytes?

like image 422
user3261349 Avatar asked Dec 10 '22 20:12

user3261349


2 Answers

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)
like image 150
Maciej Gol Avatar answered Dec 29 '22 00:12

Maciej Gol


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
like image 34
dogwynn Avatar answered Dec 29 '22 00:12

dogwynn