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)
Share:
11,049

Related videos on Youtube

user3261349
Author by

user3261349

Updated on September 15, 2022

Comments

  • user3261349
    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
      Andy about 7 years
      What is your expected result? You have an extra period in your IP.
  • user3261349
    user3261349 about 7 years
    So does socket.inet_aton(addr) return a string of 4 characters?
  • Maciej Gol about 7 years
    For 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.