Use Python to easily convert IP addresses between integers and strings.

Source: Internet
Author: User

Use Python to easily convert IP addresses between integers and strings.

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

Summary

The above is all the content of this article. I hope the content of this article will help you in your study or work. If you have any questions, please leave a message, thank you for your support.

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.