2011-04-11 16 views
35

我有一個小問題,我的腳本,我需要將表單'xxx.xxx.xxx.xxx'中的IP轉換爲整數表示,並從此表單返回。從IP字符串轉換爲整數,並在Python中向後

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` 

任何人都知道如何解決這個問題?

+2

在我的Python 2.6.6中完全不起作用:'inttoip'引發'TypeError:奇數長度的字符串'。 – Ilkka 2011-04-11 10:15:27

+0

@Ilkka對inttoip使用socket.inet_ntoa(hex(ip)[2:]。decode('hex')) – 2015-01-21 12:00:32

回答

12

你失去了打破你的字符串解碼的左零填充。

這裏有一個工作功能:

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

是的,你也將'[2:-1]'片修復爲'[2:]'那是導致我上面評論的錯誤。 – Ilkka 2011-04-11 10:18:57

+0

非常感謝。它工作正常。 – 2011-04-11 10:44:35

+0

哇,那是一行:) – 2011-04-11 11:11:15

6

下面是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)) 

不使用inet_ntop() Python代碼和struct模塊就像這個數量級慢一樣,不管它在做什麼。

+0

socket.inet_pton和inet_ntop僅在Unix上可用 – johnny 2012-09-14 15:44:19

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


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

在不使用額外的模塊純蟒

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)) 

結果:

192.168.0.1 -> 3232235521 
3232235521 -> 192.168.0.1 
17

的Python 3具有ipaddress模塊,其具有非常簡單的轉換:

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

一個線

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