Background
You have a VPN service running, but not sure if it is the VPN address or your real public address (supplied by your ISP of course), so you want to find out what is your public address and the locality of the address.
Here is the code snippet.. actually to make it more fanciful i should include a google map call…
thanks to the owner of http://canihazip.com/s, I am using the site’s info to craft a simple script.
I am using ipwhois module and my favourite request module… remember in any case if you need to get web information use requests
. ipwhois
module returns a json format with a mixture of dictionaries and lists. I use pycountry
module to lookup for the name of the country instead of standard country code such as ‘de’, ‘us’, ‘sg’, ‘cn’…
The ipwhois module seems to be only usable in Windows platform, I tried calling the ipwhois module in macOS but failed…
import requests from ipwhois import IPWhois from pycountry import countries what_is_my_ip_provider = "http://canihazip.com/s" def check_my_pub_ip(info_supplier): return requests.get(info_supplier) def where_is_my_ip(ip_address): result_obj = IPWhois(ip_address) return result_obj.lookup_whois() if __name__ == "__main__": try: response = check_my_pub_ip(what_is_my_ip_provider) info_container = where_is_my_ip(response.text) cidr = info_container["nets"][0]['cidr'] isp = info_container["nets"][0]["description"] country = countries.lookup(info_container["nets"][0]["country"]).name print("""\tIP address: {} \n Network: {} \n ISP: {} \n Country: {}""".format(response.text, cidr, isp, country)) except requests.ConnectionError as e: print(""" An error has occurred while connecting to {} \r\n This is the error description: {}""".format(what_is_my_ip_provider,e)) except requests.Timeout as e: print("""A timeout has occurred while connecting to {} \r\n This is the error description: {}""".format(what_is_my_ip_provider,e))