Search code examples
pythonhtmlserverlocation

How to get location of server based on IP address in Python


Can we program (probably in python) to get the server location from where we are accessing the webpage.

P.S. Its just for fun and to get in-depth knowledge.


Solution

  • This is an example of fetching server location using one of the APIs.

    There are many others site options such as keycdn, iplocation and more.

    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'])