The example in this article describes how Python translates IP addresses into integers. Share to everyone for your reference. The specific analysis is as follows:
Sometimes when we use the database to store IP addresses can be converted to integer storage IP address, integer occupies a small space, the index will be more convenient, the following Python code to customize a function of IP conversion to integer, very simple, the code also provides a method of converting integers to IP addresses.
Import socket, structdef Ip2long (IP): "" " Convert a IP string to Long" " Packedip = Socket.inet_aton ( IP) return struct.unpack ("! L ", Packedip) [0]
For example, the IP address of www.jb51.net is: 61.129.51.27, call the Ip2long conversion function above:
Print (' www.jb51.net IP address is%s '%ip2long (' 61.129.51.27 '))
The output is:
Www.jb51.net IP Address is 1031877403
If you want to convert an integer to an IP address, you can use the following method:
Socket.inet_ntoa (Struct.pack ('! L ', 2130706433))
The output is:
' 127.0.0.1 '
Hopefully this article will help you with Python programming.