Python访问纯真IP数据库脚本分享
2015-06-29 00:00
756 查看
项目中有这样的需求,通过IP地址判断客户端是网通的还是电信的。从同事那拿了个纯文本的IP纯真数据库,用Python写了一个小程序,感觉挺好的。下面给出实现源码:
#!/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')
相关文章推荐
- 编写Python CGI脚本的教程
- Python数据类型之字典
- Python数据类型之元组
- PAT 最大子列和问题 (Python)
- Python数据类型之列表
- Python字符串处理
- python3.x与python2.x不同点
- python __init__.py
- python遇到的问题解决方法的记录
- python设计经典Pong 游戏
- Python——特殊属性与方法
- Python并发处理
- python刷取CSDN博文访问量之四
- python刷取CSDN博文访问量之三
- python刷取CSDN博文访问量之二
- python刷取CSDN博文访问量之一
- Python源码剖析笔记3-Python执行原理初探
- Python requests 自动登录某财BBS,自动签到打卡领铜钱,最后再配个plist,每天自动执行
- 用python获取MAC地址和IP地址
- python中的面向对象编程