【问题标题】:How to get location of server based on IP address in Python如何在 Python 中根据 IP 地址获取服务器的位置
【发布时间】:2020-12-13 19:16:59
【问题描述】:

我们能否通过编程(可能在 python 中)从我们访问网页的位置获取服务器位置。

附:只是为了好玩和深入了解。

【问题讨论】:

    标签: python html server location


    【解决方案1】:

    您可以使用 bin 文件来查找 IP 地址信息。例如,使用 IP2Location Python 库和 IP2Location Lite bin 文件:

    import IP2Location
     
    IP2LocObj = IP2Location.IP2Location()
    
    IP2LocObj.open("IP2LOCATION-LITE-DB11.BIN")
    rec = IP2LocObj.get_all("8.8.8.8")
     
    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.zipcode
    print rec.timezone
    

    您可以从这里获取 IP2Location Lite 数据库:https://lite.ip2location.com/ip2location-lite

    【讨论】:

      【解决方案2】:

      这是使用其中一种 API 获取服务器位置的示例。

      还有许多其他网站选项,例如keycdniplocation 等等。

      import json
      import urllib.request
      
      GEO_IP_API_URL  = 'http://ip-api.com/json/'
      
      # Can be also site URL like this : 'google.com'
      IP_TO_SEARCH    = '87.250.250.3'
      
      # Creating request object to GeoLocation API
      req             = urllib.request.Request(GEO_IP_API_URL+IP_TO_SEARCH)
      # Getting in response JSON
      response        = urllib.request.urlopen(req).read()
      # Loading JSON from text to object
      json_response   = json.loads(response.decode('utf-8'))
      
      # Print country
      print(json_response['country'])
      

      【讨论】:

        【解决方案3】:

        您可以使用 this 等 GeoIP 工具从 IP 地址获取位置。它不是 100% 准确,但通常足够接近。

        还有诸如GeoIPpython-geoip 之类的python 模块,它们基本上可以满足您的需求。如果您想要最准确的结果,您需要从 MaxMind 购买更准确的数据库。

        【讨论】:

        • 好的!!!感谢您提供的信息,如果您能建议我一些代码行会更好。 :)
        • 更新了答案以包含一个执行相同操作的 python 模块。 @PrasunParate
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-07-01
        • 2011-03-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-11-23
        相关资源
        最近更新 更多