如何在Python中找到IP地址的位置?

Mul*_*ala 18 python

我正在开发一个项目,需要在我的数据库中存储用户位置.我得到了该用户的公共IP地址.但我无法获得用户位置.我尝试了几种方法(来自StackOverflow),但我没有找到任何提示.如下所示

url = urllib.urlopen("http://api.hostip.info/get_html.php?ip=%s&position=true" % ip)
data = re.compile('^[^\(]+\(|\)$').sub('', url.read())
print data
Run Code Online (Sandbox Code Playgroud)

但我得到的结果是

Unknown Country?) (XX)
City: (Unknown City?)
Run Code Online (Sandbox Code Playgroud)

其他方式:

import urllib

response = urllib.urlopen("http://api.hostip.info/get_html.php?ip={}&position=true".format(ip)).read()

print(response)
Run Code Online (Sandbox Code Playgroud)

但结果是

Country: (Unknown Country?) (XX)
City: (Unknown City?)

Latitude: 
Longitude: 
IP: 115.xxx.xxx.xx
Run Code Online (Sandbox Code Playgroud)

任何帮助,将不胜感激!

小智 12

感谢所有解决方案和解决方法!但是,我无法使用上述所有方法。

这是对我有用的:

import requests

response = requests.get("https://geolocation-db.com/json/39.110.142.79&position=true").json()
Run Code Online (Sandbox Code Playgroud)

这种方法看起来简单易用。(我需要使用字典响应...)

将来,“geolocation-db.com”可能会变得不可用,因此可能需要其他来源!


xec*_*cgr 11

尝试使用pygeoip

~$ ping stackoverflow.com
PING stackoverflow.com (198.252.206.16) 56(84) bytes of data.

>>> import pygeoip
>>> GEOIP = pygeoip.GeoIP("/absolute_path/GeoIP.dat", pygeoip.MEMORY_CACHE)
>>> GEOIP.country_name_by_addr(ip)
'United States'
Run Code Online (Sandbox Code Playgroud)

GeoIP.data可在此处获得

  • 它看起来已被弃用。 (4认同)

She*_*ary 10

获取IP地址以及详细位置的最简单方法之一是使用http://ipinfo.io

import re
import json
from urllib2 import urlopen

url = 'http://ipinfo.io/json'
response = urlopen(url)
data = json.load(response)

IP=data['ip']
org=data['org']
city = data['city']
country=data['country']
region=data['region']

print 'Your IP detail\n '
print 'IP : {4} \nRegion : {1} \nCountry : {2} \nCity : {3} \nOrg : {0}'.format(org,region,country,city,IP)
Run Code Online (Sandbox Code Playgroud)

  • 事实证明,他们制作了自己的 Python 库!https://github.com/ipinfo/python 又名 `pip install ipinfo` (2认同)
  • @AlihaydarGubatov 刚刚创建了一个帐户。每月最多 50,000 美元免费,无需付款信息。 (2认同)

Kur*_*den 9

您可以使用https://geolocation-db.com的服务支持 IPv4 和 IPv6。返回 JSON 对象或 JSONP 回调函数。

蟒蛇2:

import urllib
import json

url = "https://geolocation-db.com/json"
response = urllib.urlopen(url)
data = json.loads(response.read())
print data
Run Code Online (Sandbox Code Playgroud)

蟒蛇3:

import urllib.request
import json

with urllib.request.urlopen("https://geolocation-db.com/json") as url:
    data = json.loads(url.read().decode())
    print(data)
Run Code Online (Sandbox Code Playgroud)

一个 python 3 jsonp 示例:

import urllib.request
import json

with urllib.request.urlopen("https://geolocation-db.com/jsonp/8.8.8.8") as url:
    data = url.read().decode()
    data = data.split("(")[1].strip(")")
    print(data)
Run Code Online (Sandbox Code Playgroud)


小智 6

假设您已经获得了IP地址,则可以尝试使用IP2Location Python库获取用户位置。示例代码如下:

import os
import IP2Location

database = IP2Location.IP2Location(os.path.join("data", "IPV4-COUNTRY.BIN"))

rec = database.get_all(ip)

print(rec.country_short)
print(rec.country_long)
print(rec.region)
print(rec.city)
print(rec.isp)  
print(rec.latitude)
print(rec.longitude)            
print(rec.domain)
print(rec.zipcode)
print(rec.timezone)
print(rec.netspeed)
print(rec.idd_code)
print(rec.area_code)
print(rec.weather_code)
print(rec.weather_name)
print(rec.mcc)
print(rec.mnc)
print(rec.mobile_brand)
print(rec.elevation)
print(rec.usage_type)
Run Code Online (Sandbox Code Playgroud)

根据您的要求,例如,如果要获取用户的国家名和地区名,则可以执行以下操作:

import os
import IP2Location

database = IP2Location.IP2Location(os.path.join("data", "IPV4-COUNTRY.BIN"))

rec = database.get_all(ip)

user_country = rec.country_long
user_region = rec.region
Run Code Online (Sandbox Code Playgroud)

有关更多详细信息,您可以访问这里:IP2Location Python库

Github链接:IP2Location Python库Github

  • 很棒的离线解决方案。 (2认同)

小智 6

我发现 ipinfo 提供最好的服务,并提供每月最多 50k 次调用的免费 API 使用 - 请参阅此处的“速率限制” :

import ipinfo

access_token = '123456789abc'
handler = ipinfo.getHandler(access_token)
ip_address = '216.239.36.21'
details = handler.getDetails(ip_address)
details.city
'Mountain View'
details.country
'US'
details.loc
'37.3861,-122.0840'
Run Code Online (Sandbox Code Playgroud)


Er *_*ore 5

对于python-3.x

def ipInfo(addr=''):
    from urllib.request import urlopen
    from json import load
    if addr == '':
        url = 'https://ipinfo.io/json'
    else:
        url = 'https://ipinfo.io/' + addr + '/json'
    res = urlopen(url)
    #response from url(if res==None then check connection)
    data = load(res)
    #will load the json response into data
    for attr in data.keys():
        #will print the data line by line
        print(attr,' '*13+'\t->\t',data[attr])
Run Code Online (Sandbox Code Playgroud)