Skip to content

Instantly share code, notes, and snippets.

@inactivist
Last active December 25, 2015 13:19
Show Gist options
  • Save inactivist/6982792 to your computer and use it in GitHub Desktop.
Save inactivist/6982792 to your computer and use it in GitHub Desktop.
Request the current 'external' (Internet-facing) IP address as reported by http://httpbin.org/io and send it to stdout. Useful if you are running on a 'net connection with a non-static IP address. This probably won't do much for you if you're behind a proxy.
#!/usr/bin/env python
"""
Get the 'external' IP address using httpbin.org JSON API.
(http://httpbin.org/ip)
Author: Michael Curry (thatmichaelcurry [at] gmail)
Requires requests 2 or higher.
http://httpbin.org/ip responds with the following JSON snippet:
{
origin: "a.b.c.d"
}
Distributed under the MIT license. No warrantees!
http://opensource.org/licenses/MIT
"""
import requests
import sys
# TIMEOUT is used by requests.get() to control the response timeout.
# http://docs.python-requests.org/en/latest/user/quickstart/#timeouts
TIMEOUT = 5
try:
r = requests.get('http://httpbin.org/ip', timeout=TIMEOUT)
extern_ip = r.json()['origin']
print extern_ip
sys.exit(0)
except KeyError as e:
err = u"Response did not contain expected value '{0}'.".format(e.message)
except requests.exceptions.ConnectionError as e:
err = u"Server connection error."
except Exception as e:
err = u"{0}".format(e)
sys.stderr.write(u"error: " + err + u"\n")
sys.exit(1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment