最新消息:自律使人变得更强大

python怎么实现IP定位

admin 1047 次 0 条
调用第三方接口查询ip归属地
https://open.onebox.so.com/dataApi?type=ip&src=onebox&tpl=0&num=1&query=ip&ip=123.123.47.11

import httplib, json

ip = '123.123.47.11'
ip = raw_input("请输入一个Ip:")

httpClient = None

try:
    httpClient = httplib.HTTPSConnection('open.onebox.so.com', 443, timeout=30)
    requestURL = '/dataApi?type=ip&src=onebox&tpl=0&num=1&query=ip&ip={}'.format(ip)
    httpClient.request('GET', requestURL)

    response = httpClient.getresponse()

    if response.status == 200:
        obj = json.loads(response.read())
        #print obj
        if obj['0']:
            print obj['0'], obj['1'], obj['3'], obj['5']
        else:
            print obj['4']

except Exception, e:
    print e
finally:
    if httpClient:
        httpClient.close()

#将ip转换成整形数字
def ipToLong(ip):
    arr = ip.split('.')
    return (int(arr[0]) << 24) + (int(arr[1]) << 16) + (int(arr[2]) << 8) + (int(arr[3]) << 0)


ip = '100.4.5.6'
num = ipToLong(ip)
print num

110.96.0.0  110.127.255.255

print ipToLong('110.96.0.0')
print ipToLong('110.127.255.255')
print '---------------'

print ipToLong('110.127.1.255')
print ipToLong('110.96.1.1')
print ipToLong('110.97.0.0')

print '----------'
print ipToLong('0.0.0.0')
print ipToLong('0.255.255.255')


dict = {}
#读取数据
ipline = '58.211.91.56,58.211.91.63,江苏省苏州市 东山精密制造股份有限公司(吴中区东山镇工业园凤凰山路8号)'
arr = ipline.split(',')
sindex = ipToLong(arr[0])
eindex = ipToLong(arr[1])
#创建索引
for index in range(sindex, eindex+1):
    dict[index] = arr[2]

#print dict

#ip
uip = ipToLong('58.211.91.57')
#直接查询Ip
print dict[uip]
发表我的评论

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址