Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a function for Converting IP address to decimal number in python?

Tags:

python

decimal

ip

Is there any function or API or method that will convert a doted IP string to decimal number?

like image 770
Mir Khashkhash Avatar asked Jul 21 '11 23:07

Mir Khashkhash


1 Answers

I'm not sure what is the decimal number you really want, but take a look at socket.inet_aton. It will give you string with binary representation of the IP address in network byte order. If you want to get a regular integer out of it, you could use struct.unpack with either "!I" or "I", depending on which byte order you're interested in.

Example:

import socket, struct
print struct.unpack("!I", socket.inet_aton("127.0.0.1"))[0]

Prints: 2130706433.

like image 180
tomasz Avatar answered Nov 14 '22 21:11

tomasz