How to use Python to convert an IP address between an integer and a string

Source: Internet
Author: User
This article describes how to use Python to easily convert IP addresses between integers and strings, this article also shares with you how to use regular expressions in Python to verify whether a string is an IP address. For more information, see the following. This article describes how to use Python to easily convert IP addresses between integers and strings, this article also shares with you how to use regular expressions in Python to verify whether a string is an IP address. For more information, see the following.

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\d?)\.){3}(25[0-5]|2[0-4]\d|[01]?\d\d?)$')  if p.match(ip):  return True  else:  return False

Summary

The above is a detailed description of how to use Python to convert IP addresses between integer and string types. For more information, see other related articles in the first PHP community!

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.