从IPstring转换为整数,并在Python中向后

我有一个小问题,我的脚本,在那里我需要将表单'xxx.xxx.xxx.xxx'的IP转换为整数表示,并从这种forms回来。

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` 

任何人都知道如何解决这个问题?

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

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

结果:

 192.168.0.1 -> 3232235521 3232235521 -> 192.168.0.1 

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

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

你失去了打破你的string解码的左零填充。

这是一个工作function:

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

以下是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()struct模块的Python代码比这慢了很多,不pipe它在做什么。

你也可以使用reduce来简单地使用函数式编程

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

基本上这一行呢

 out = 0 out << 8 + 127 out << 8 + 0 out << 8 + 0 out << 8 + 1