This article describes how to use Python to easily convert IP addresses between integers and strings, this article also shares with you how to use regular expressions in Python to verify whether a string is an IP address. For more information, see the following. This article describes how to use Python to easily convert IP addresses between integers and strings, this article also shares with you how to use regular expressions in Python to verify whether a string is an IP address. For more information, see the following.
Preface
Everyone should have some experience. it is really a waste of space and performance for storing string-type IP addresses in the database, so cute people want to convert IP addresses to integer storage. INET exists in MySQL_ATON()
,INET_NTOA()
If the function is used to convert an integer from an IP address to a string, which of the following methods can be used in MySQL?INET_ATON()
,INET_NTOA()
? There must be some methods ~
The method is as follows:
# Import the relevant module package import socketimport struct # Convert the IP from string to integer type> int (socket. inet_aton ('2017. 0.0.1 '). encode ('Hex'), 16) 2130706433 # Convert an IP address from an integer to a string >>> socket. inet_ntoa (struct. pack ("! I ", 2130706433) '2017. 0.0.1'
Expansion
In Python, regular expressions are used to verify whether a string is an IP address.
def checkip(ip): p = re.compile('^((25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(25[0-5]|2[0-4]\d|[01]?\d\d?)$') if p.match(ip): return True else: return False
Summary
The above is a detailed description of how to use Python to convert IP addresses between integer and string types. For more information, see other related articles in the first PHP community!