The method of using Python to transform IP between integer and string

Source: Internet
Author: User
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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.