Home > Backend Development > Python Tutorial > python将ip地址转换成整数的方法

python将ip地址转换成整数的方法

WBOY
Release: 2016-06-10 15:17:08
Original
1456 people have browsed it

本文实例讲述了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]
Copy after login

例如 www.jb51.net的ip地址为:61.129.51.27,调用上面的ip2long转换函数:

print('www.jb51.net ip address is %s'%ip2long('61.129.51.27'))
Copy after login

输出结果为:

www.jb51.net ip address is 1031877403
Copy after login

如果要将整数转换成ip地址,可以使用下面的方法:

socket.inet_ntoa(struct.pack('!L', 2130706433))
Copy after login

输出结果为:

'127.0.0.1'
Copy after login

希望本文所述对大家的Python程序设计有所帮助。

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