免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 3954 | 回复: 0
打印 上一主题 下一主题

二分法查找IP国家代码 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2009-11-12 23:16 |只看该作者 |倒序浏览

               
               
               
                #!/usr/bin/env python
import os
import struct
import socket

def ipToInt(ip):
    return struct.unpack("!I",socket.inet_aton(ip))[0]
def loadRegion():
    # apnic|CN|ipv4|58.16.0.0|65536|20050125|allocated
    regionList = []
    regionFile = 'regionmap.txt'
    if not os.path.isfile(regionFile): return []
    for line in open(regionFile,'r').readlines():
        line = line.strip()
        if line.find('ipv4')>-1:
            try:
                l = line.split('|')
                country = l[1]
                if country == 'ZZ': continue
                data = {}
                ipaddr = l[3]
                offset = l[4]
                ipInt = ipToInt(ipaddr)
                data[ipInt] = (offset,country)
                regionList.append(data)
            except Exception,e:
                pass
    return regionList
def binSearch(regionList, regionListLen, ipInt):
    try:
        low = 0
        high = regionListLen
        
        while low = high:
            mid = (low + high)/2
            if regionList[mid].keys()[0] == ipInt:
                return mid
         
            if regionList[mid].keys()[0] > ipInt and ipInt > regionList[mid-1].keys()[0]:
                return mid - 1
            if regionList[mid].keys()[0] > ipInt:
                high = mid - 1
            else:
                low = mid + 1
        return ''
    except Exception,e:
        return ''
def findCountry(regionList, regionListLen, ipaddr):
    try:
        ipaddr = ipToInt(ipaddr)
        rindex = binSearch(regionList, regionListLen, ipaddr)
        offset,region = regionList[rindex].items()[0][1]
        if (int(regionList[rindex].keys()[0]) + int(offset)) >= ipaddr:
            return region
        else:
            return '**'
    except:
        return '**'   
if __name__=='__main__':
    regionList = loadRegion()
    regionList.sort()
    regionListLen = len(regionList) - 1
    print findCountry(regionList, regionListLen, '127.0.0.1')
    print findCountry(regionList, regionListLen, '130.23.44.23')
    print findCountry(regionList, regionListLen, '218.12.250.3')
$python ipcountry.py
**
US
CN
效率一般般,查找100万条记录用了1分钟左右时间。


本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u3/105486/showart_2093073.html
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP