Chinaunix首页 | 论坛 | 博客
  • 博客访问: 207311
  • 博文数量: 32
  • 博客积分: 3319
  • 博客等级: 中校
  • 技术积分: 340
  • 用 户 组: 普通用户
  • 注册时间: 2009-12-26 21:40
文章分类

全部博文(32)

文章存档

2010年(31)

2009年(1)

分类: Python/Ruby

2010-04-23 14:34:07

#!/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


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