Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert an IP string to a number and vice versa

Tags:

python

django

How would I use python to convert an IP address that comes as a str to a decimal number and vice versa?

For example, for the IP 186.99.109.000 <type'str'>, I would like to have a decimal or binary form that is easy to store in a database, and then retrieve it.

like image 574
user987055 Avatar asked Mar 06 '12 20:03

user987055


1 Answers

converting an IP string to long integer:

import socket, struct  def ip2long(ip):     """     Convert an IP string to long     """     packedIP = socket.inet_aton(ip)     return struct.unpack("!L", packedIP)[0] 

the other way around:

>>> socket.inet_ntoa(struct.pack('!L', 2130706433)) '127.0.0.1' 
like image 198
Not_a_Golfer Avatar answered Sep 21 '22 17:09

Not_a_Golfer