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

  • 2020-05-27 06:00:21
  • OfStack


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('').encode('hex'),16)
#  will IP From integer to string 
>>> socket.inet_ntoa(struct.pack("!I",2130706433))


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 
 return False 


Related articles: