Python's method of converting IP addresses to integers

  • 2020-04-02 14:40:59
  • OfStack

This article illustrates how python converts IP addresses to integers. Share with you for your reference. Specific analysis is as follows:

Sometimes when we use the database to store the IP address can be converted to integer IP address storage, integer space is small, index will be more convenient, the python code below a custom IP into integer function, very simple, the code also provides the integer into IP address method.


import socket, struct
def ip2long(ip):
  """
  Convert an 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, and the above ip2long conversion function is called:


print('www.jb51.net ip address is %s'%ip2long('61.129.51.27'))

The output result is:


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))

The output result is:


'127.0.0.1'

I hope this article has helped you with your Python programming.


Related articles: