Python converts an IP address to an integer.
This example describes how python converts an IP address to an integer. 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:
'2017. 0.0.1'
I hope this article will help you with Python programming.