Easily convert an IP address between an integer and a string using Python


preface

As you all know, a string IP in a database is a real waste of space and performance, so the cute guys came up with the idea of converting IP to integer storage. MySQL has INET _ATON() , INET_NTOA() The IP function converts between an IP integer and a string. What methods exist in Python to implement MySQL INET_ATON() , INET_NTOA() What about the function? There must be a way

Methods the following

#  Import the related module package
import socket
import struct
#  will IP From string to integer
>>> int(socket.inet_aton('127.0.0.1').encode('hex'),16)
2130706433
#  will IP From integer to string
>>> socket.inet_ntoa(struct.pack("!I",2130706433))
'127.0.0.1'

expand

Under Python, a regular expression is used to match and 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

conclusion