Skip to content

Instantly share code, notes, and snippets.

@sha1n
Last active March 11, 2020 10:28
Show Gist options
  • Select an option

  • Save sha1n/e6963da4f6c38214bd62617e03f16ee6 to your computer and use it in GitHub Desktop.

Select an option

Save sha1n/e6963da4f6c38214bd62617e03f16ee6 to your computer and use it in GitHub Desktop.
An 'ipify.org' based public IP resolution code in Python
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