Say i have an IP address in python
addr = '164.107.113.18'
How do i convert the IP address into 4 bytes?
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)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With