4

Say i have an IP address in python

addr = '164.107.113.18'

How do i convert the IP address into 4 bytes?

2
  • 1
    What is your expected result? You have an extra period in your IP. Commented Oct 20, 2015 at 19:02
  • That was a syntax error on my part. Commented Oct 20, 2015 at 19:11

2 Answers 2

11

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)
Sign up to request clarification or add additional context in comments.

2 Comments

So does socket.inet_aton(addr) return a string of 4 characters?
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.
3

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.