Use Python to easily convert IP addresses between integers and strings.
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 ?) \.) {3} (25 [0-5] | 2 [0-4] \ d | [01]? \ D ?) $ ') If p. match (ip): return True else: return False
Summary
The above is all the content of this article. I hope the content of this article will help you in your study or work. If you have any questions, please leave a message, thank you for your support.