python访问纯真IP数据库的代码
2024-08-22 18:05:29
通过IP地址判断客户端是网通的还是电信的。
使用一个纯文本的IP纯真数据库,用Python写了一个小程序。
核心代码:
- #!/usr/bin/env python
- #site www.jbxue.com
- #
- # -*- 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')
最新文章
- SharePoint 2013 Search 配置总结
- 学习iOS前我们需要知道的事情
- fastCGI与PHP-fpm
- 第一个android应用程序
- Windows 窗体启动和关闭的事件顺序
- Upgrading to MySQL 5.7---focusing on temporal types
- java_Cookie添加和删除
- DataReader 和 DataSet 的区别
- 基于MINA框架快速开发网络应用程序
- ASP.NET Core 使用 JWT 搭建分布式无状态身份验证系统
- 关于DataTable序列化的事儿
- Pair Project1:电梯控制程序
- java运行报错:nested exception is java.lang.NoSuchFieldError: INSTANCE,但使用@Test测试是好的
- shared_ptr(作为局部变量返回)
- Java高并发综合
- js异步原理与 Promise
- java 通过调用存储过程获取结果集
- java 基础 --final--008
- 聊聊flink的Async I/O
- 洛谷P1434 滑雪
热门文章
- bash中的快捷键使用
- 解决myeclipse不编译的方法
- android基础知识复习——RelativeLayout布局属性、背景、半透明设置(XML设置)
- daemon函数的原理及使用详解
- Caused by: org.apache.ibatis.reflection.ReflectionException我碰到的情况,原因不唯一
- 解决 java.lang.ClassNotFoundException配置文件出错的问题
- C# 中的";yield";与 ";yield break";使用
- redis学习笔记——命令执行流程
- 算法笔记_090:蓝桥杯练习 7-1用宏求球的体积(Java)
- hibernate 关系映射之 双向外键关联一对一