Python訪問純真IP資料庫指令碼分享

來源:互聯網
上載者:User
項目中有這樣的需求,通過IP地址判斷用戶端是網通的還是電信的。從同事那拿了個純文字的IP純真資料庫,用Python寫了一個小程式,感覺挺好的。下面給出實現源碼:

#!/usr/bin/env python# -*- coding: utf-8 -*-from bisect import bisect_LIST1, _LIST2 = [], []_INIT = Falseip2int = 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')
  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.