This article describes how to convert an IP address to an integer in python. it involves the IP address conversion technique in Python, for more information about how to convert an IP address to an integer in python, see the following example. Share it with you for your reference. The specific analysis is as follows:
Sometimes, when we use a database to store IP addresses, we can convert the IP addresses to integer storage. the integer storage space is small and the index is more convenient, the following python code defines a function for converting an ip address to an integer, which is very simple. The Code also provides a method for converting an integer to an ip address.
import socket, structdef ip2long(ip): """ Convert an IP string to long """ packedIP = socket.inet_aton(ip) return struct.unpack("!L", packedIP)[0]
For example, if the IP address of www.jb51.net is 61.129.51.27, call the above ip2long conversion function:
print('www.jb51.net ip address is %s'%ip2long('61.129.51.27'))
Output result:
www.jb51.net ip address is 1031877403
To convert an integer to an IP address, use the following method:
socket.inet_ntoa(struct.pack('!L', 2130706433))
Output result:
'127.0.0.1'
I hope this article will help you with Python programming.