萬盛學電腦網

 萬盛學電腦網 >> 網絡編程 >> 編程語言綜合 >> Python訪問純真IP數據庫腳本分享

Python訪問純真IP數據庫腳本分享

   這篇文章主要介紹了Python訪問純真IP數據庫腳本分享,本文直接給出實現代碼,需要的朋友可以參考下

  項目中有這樣的需求,通過IP地址判斷客戶端是網通的還是電信的。從同事那拿了個純文本的IP純真數據庫,用Python寫了一個小程序,感覺挺好的。下面給出實現源碼:

  ?

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 #!/usr/bin/env python # -*- coding: utf-8 -*-   from bisect import bisect   _LIST1, _LIST2 = [], [] _INIT = False   ip2int = lambda ip_str: reduce(lambda a, b: (a << 8) + b, [int(i) for i in ip_str.split('.')])   def _init(): global _LIST, _INIT if not _INIT: for l in open('ipdata.txt', 'rb'): ip1, ip2 = l.split()[:2] addr = ' '.join(l.split()[2:]) ip1, ip2 = ip2int(ip1), ip2int(ip2) _LIST1.append(ip1) _LIST2.append((ip1, ip2, addr)) _INIT = True   def ip_from(ip): _init() i = ip2int(ip) idx = bisect(_LIST1, i) assert(idx > 0) if len(_LIST1) <= idx: return u'unknown ip address %s' % ip else: frm, to ,addr = _LIST2[idx - 1] if frm <= i <= to: return addr else: return u'unknown ip address %s' % ip   if __name__ == '__main__': print ip_from('115.238.54.106') print ip_from('220.181.29.160') print ip_from('115.238.54.107') print ip_from('8.8.8.8')
copyright © 萬盛學電腦網 all rights reserved