[翻译]  Conversion from IP string to integer, and backward in Python

[CHINESE]  从IP字符串转换为整数,在Python中向后转换


i have a little problem with my script, where i need to convert ip in form 'xxx.xxx.xxx.xxx' to integer representation and go back from this form.

我的脚本有一点问题,我需要将表单'xxx.xxx.xxx.xxx'中的ip转换为整数表示,然后从此表单返回。

def iptoint(ip):
    return int(socket.inet_aton(ip).encode('hex'),16)

def inttoip(ip):
    return socket.inet_ntoa(hex(ip)[2:].decode('hex'))


In [65]: inttoip(iptoint('192.168.1.1'))
Out[65]: '192.168.1.1'

In [66]: inttoip(iptoint('4.1.75.131'))
---------------------------------------------------------------------------
error                                     Traceback (most recent call last)

/home/thc/<ipython console> in <module>()

/home/thc/<ipython console> in inttoip(ip)

error: packed IP wrong length for inet_ntoa`

Anybody knows how to fix that?

有人知道如何解决这个问题吗?

6 个解决方案

#1


67  

def ip2int(addr):                                                               
    return struct.unpack("!I", socket.inet_aton(addr))[0]                       


def int2ip(addr):                                                               
    return socket.inet_ntoa(struct.pack("!I", addr))                            

#2


18  

Python 3 has ipaddress module which features very simple conversion:

Python 3有ipaddress模块​​,它具有非常简单的转换:

int(ipaddress.IPv4Address("192.168.0.1"))
str(ipaddress.IPv4Address(3232235521))

#3


17  

In pure python without use additional module

在纯python中没有使用额外的模块

def IP2Int(ip):
    o = map(int, ip.split('.'))
    res = (16777216 * o[0]) + (65536 * o[1]) + (256 * o[2]) + o[3]
    return res


def Int2IP(ipnum):
    o1 = int(ipnum / 16777216) % 256
    o2 = int(ipnum / 65536) % 256
    o3 = int(ipnum / 256) % 256
    o4 = int(ipnum) % 256
    return '%(o1)s.%(o2)s.%(o3)s.%(o4)s' % locals()

# Example
print('192.168.0.1 -> %s' % IP2Int('192.168.0.1'))
print('3232235521 -> %s' % Int2IP(3232235521))

Result:

结果:

192.168.0.1 -> 3232235521
3232235521 -> 192.168.0.1

#4


12  

You lose the left-zero-padding which breaks decoding of your string.

你失去了左零填充,这会破坏你的字符串的解码。

Here's a working function:

这是一个有效的功能:

def inttoip(ip):
    return socket.inet_ntoa(hex(ip)[2:].zfill(8).decode('hex'))

#5


6  

Below are the fastest and most straightforward (to the best of my knowledge) convertors for IPv4 and IPv6:

以下是最快,最直接(据我所知)IPv4和IPv6的转换器:

    try:
        _str = socket.inet_pton(socket.AF_INET, val)
    except socket.error:
        raise ValueError
    return struct.unpack('!I', _str)[0]
    -------------------------------------------------
    return socket.inet_ntop(socket.AF_INET, struct.pack('!I', n))
    -------------------------------------------------
    try:
        _str = socket.inet_pton(socket.AF_INET6, val)
    except socket.error:
        raise ValueError
    a, b = struct.unpack('!2Q', _str)
    return (a << 64) | b
    -------------------------------------------------
    a = n >> 64
    b = n & ((1 << 64) - 1)
    return socket.inet_ntop(socket.AF_INET6, struct.pack('!2Q', a, b))

Python code not using inet_ntop() and struct module is like order of magnitude slower than this regardless of what it is doing.

不使用inet_ntop()和struct模块的Python代码与此相比要慢几个数量级,无论它在做什么。

#6


1  

One line

一条线

reduce(lambda out, x: (out << 8) + int(x), '127.0.0.1'.split('.'), 0)

注意!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。



 
© 2014-2018 ITdaan.com 粤ICP备14056181号