Python将ip地址转换为ip号码?

时间:2015-01-15 19:56:16

标签: python formatting ip

我正在迭代一系列ips,以从Maxmind数据库中提取与它们相关联的组织名称。我想从ip空间中的第一个ip开始,并说继续直到ips具有相同的组织名称,然后打印范围!

def incrementIP(ip):
    if ip == '224.0.0.0':
        return 'end'
    nip = struct.unpack('>I', socket.inet_aton(ip))[0]  # This line convers IP string to number
    nip += 1
    ip = socket.inet_ntoa(struct.pack('>I',nip)) # This line converts the number back to IP
    return(ip)

d = {}
IPaddress = '0.0.0.1'
while IPaddress != 'end':
    org = (gi.org_by_addr(IPaddress))
    d.setdefault(org,[]).append(gi.range_by_ip(IPaddress))
    IPaddress = incrementIP(gi.range_by_ip(IPaddress)[1])

这是我得到的错误

---------------------------------------------------------------------------
error                                    
 Traceback (most recent call last)
<ipython-input-16-a010e0aa70ac> in <module>()
      4     org = (gi.org_by_addr(IPaddress))
      5     d.setdefault(org,[]).append(gi.range_by_ip(IPaddress))
----> 6     IPaddress = incrementIP(gi.range_by_ip(IPaddress)[1])
      7 #     print (d)
      8 

<ipython-input-14-0b40331de68c> in incrementIP(ip)
      7     nip = struct.unpack('>I', socket.inet_aton(ip))[0]  # This line convers IP string to number
      8     nip += 1
----> 9     ip = socket.inet_ntoa(struct.pack('>I',nip)) # This line converts the number back to IP
     10     return(ip)

error: 'I' format requires 0 <= number <= 4294967295

我无法确定为什么会收到此错误。有人可以帮我吗?

0 个答案:

没有答案