Home >Backend Development >Python Tutorial >How to use Python to convert IP between integers and strings

How to use Python to convert IP between integers and strings

Y2J
Y2JOriginal
2017-05-04 11:57:281739browse

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'

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

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!

Statement:
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