python将ip地址转换成整数的方法
Jun 10, 2016 pm 03:17 PM本文实例讲述了python将ip地址转换成整数的方法。分享给大家供大家参考。具体分析如下:
有时候我们用数据库存储ip地址时可以将ip地址转换成整数存储,整数占用空间小,索引也会比较方便,下面的python代码自定义了一个ip转换成整数的函数,非常简单,代码同时还提供了整数转换成ip地址的方法。
import socket, struct def ip2long(ip): """ Convert an IP string to long """ packedIP = socket.inet_aton(ip) return struct.unpack("!L", packedIP)[0]
例如 www.jb51.net的ip地址为:61.129.51.27,调用上面的ip2long转换函数:
print('www.jb51.net ip address is %s'%ip2long('61.129.51.27'))
输出结果为:
www.jb51.net ip address is 1031877403
如果要将整数转换成ip地址,可以使用下面的方法:
socket.inet_ntoa(struct.pack('!L', 2130706433))
输出结果为:
'127.0.0.1'
希望本文所述对大家的Python程序设计有所帮助。

Hot Article

Hot tools Tags

Hot Article

Hot Article Tags

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

How to set font size on mobile phone (easily adjust font size on mobile phone)

What are the advantages and disadvantages of templating?

Google AI announces Gemini 1.5 Pro and Gemma 2 for developers

How to choose a mobile phone screen protector to protect your mobile phone screen (several key points and tips for purchasing mobile phone screen protectors)
