This article mainly introduces the use of Python IP in the integer and the string between the easy conversion of relevant information, the text also share with you the use of a regular expression in Python to match check whether a string is an IP address method, the need for friends can refer to the following to see together.
Objective
Everyone should have some experience, for the string type of IP into the database, is a waste of space and wasted performance of the guy, so cute people want to come out to convert IP to integer storage. MySQL exists in the inet _ATON()
, the INET_NTOA()
function of IP integer and the conversion between the string, then there is what method in Python can INET_ATON()
realize INET_NTOA()
the function of MySQL? There must be some way.
Methods are as follows
# import the associated module package import socketimport struct# the IP from string to integer >>> int (Socket.inet_aton (' 127.0.0.1 '). Encode (' hex '), 16) 2130706433# convert IP from int to string >>> socket.inet_ntoa ("! I ", 2130706433)) ' 127.0.0.1 '
Expand
Using regular expressions in Python to match the checksum of a string for 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
Summarize