文章详情

  • 游戏榜单
  • 软件榜单
关闭导航
热搜榜
热门下载
热门标签
php爱好者> php文档>Python查找IP国家代码

Python查找IP国家代码

时间:2010-04-23  来源:pywugw

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


相关阅读 更多 +
排行榜 更多 +
找茬脑洞的世界安卓版

找茬脑洞的世界安卓版

休闲益智 下载
滑板英雄跑酷2手游

滑板英雄跑酷2手游

休闲益智 下载
披萨对对看下载

披萨对对看下载

休闲益智 下载