Last active
March 11, 2020 10:28
-
-
Save sha1n/e6963da4f6c38214bd62617e03f16ee6 to your computer and use it in GitHub Desktop.
An 'ipify.org' based public IP resolution code in Python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import http.client as http | |
| def resolve_my_public_ip(timeout_sec=1.0): | |
| print("Trying to resolve public IP...") | |
| conn = http.HTTPSConnection( | |
| host='api.ipify.org', | |
| port=None, | |
| timeout=timeout_sec, | |
| ) | |
| response = None | |
| try: | |
| conn.request( | |
| method='GET', | |
| url='', | |
| headers={'Accept': 'text/plain'} | |
| ) | |
| response = conn.getresponse() | |
| if response.status == 200: | |
| print("Public IP resolved successfully.") | |
| return response.read().decode('UTF-8').strip() | |
| else: | |
| return None | |
| finally: | |
| if response is not None: | |
| response.close() | |
| conn.close() | |
| if __name__ == '__main__': | |
| print('Your public IP is: {ip}'.format(ip=resolve_my_public_ip())) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment