How to use Python to convert IP between integers and strings

Y2J
Release: 2017-05-04 11:57:28
Original
1729 people have browsed it

This article mainly introduces you to the relevant information about using Python to easily convert IP between integers and strings. The article also shares with you the use of regular expressions in Python to match and verify whether a string is Friends who need it can refer to the IP address method. Let’s take a look below.

Preface

Everyone should have realized that storing string IP in the database is a waste of space and waste. Performance guys, so the lovely people figured out to convert the IP to integer storage. There are INET_ATON() and INET_NTOA() functions in MySQL to convert between IP integers and strings, then Python Are there any methods that can realize the functions of INET_ATON() and INET_NTOA() in MySQL? There must be a method~

The method is as follows

# 导入相关模块包
import socket
import struct
# 将IP从字符串转为整型
>>> int(socket.inet_aton('127.0.0.1').encode('hex'),16)
2130706433
# 将IP从整型转为字符串
>>> socket.inet_ntoa(struct.pack("!I",2130706433))
'127.0.0.1'
Copy after login

Expand

Use regular expressions in Python 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
Copy after login

Summary

The above is the detailed content of How to use Python to convert IP between integers and strings. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!