Chinaunix首页 | 论坛 | 博客
  • 博客访问: 35852
  • 博文数量: 13
  • 博客积分: 1415
  • 博客等级: 上尉
  • 技术积分: 140
  • 用 户 组: 普通用户
  • 注册时间: 2009-11-06 10:48
文章分类

全部博文(13)

文章存档

2011年(1)

2009年(12)

我的朋友
最近访客

分类: Python/Ruby

2009-11-12 23:16:57

#!/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分钟左右时间。

阅读(663) | 评论(1) | 转发(0) |
给主人留下些什么吧!~~

chinaunix网友2009-11-13 09:31:41

在用你的例子学习python 很有帮助 多谢 能否把你的regionmap.txt下载处也显示呢