Skip to content

Instantly share code, notes, and snippets.

@pavgup
Created April 25, 2013 10:02
Show Gist options
  • Select an option

  • Save pavgup/5458750 to your computer and use it in GitHub Desktop.

Select an option

Save pavgup/5458750 to your computer and use it in GitHub Desktop.
#!/usr/bin/python
import urllib2
import threading
import re
import Queue
import sys
# The fourth URL returns a 403 error which python dies on, so I wrap this grab_ip function with exception handling.
# This function (and thereby thread) only acts if it sees a HTTP 200 return code.
# The regex for onlyIP grabs all of the IP addresses in the HTTP response and I just return the first IP in that list (which should be the right IP).
# And this function puts this IP address onto the ip_queue that was passed to it which is a clean asynchronous signalling mechanism for the main thread.
def grab_ip(url, ip_queue):
try:
urlResource = urllib2.urlopen(url)
if urlResource.getcode() == 200:
data = urlResource.read()
onlyIP = re.findall(r'[0-9]+(?:\.[0-9]+){3}',data)
ip_queue.put(onlyIP[0])
except:
pass
# I did not know about Python's Queue module before this, but it is awesome. Highly functional asynchronous data tool. Awesome. And core python!
ip_queue = Queue.Queue()
# In retrospect, I really should have just had a variable that was parsed by a simple for loop, but here are the threads all spelled out.
first = threading.Thread(target=grab_ip, args=("http://checkip.amazonaws.com/", ip_queue))
first.daemon = True
first.start()
second = threading.Thread(target=grab_ip, args=("http://checkip.dyndns.org/", ip_queue))
second.daemon = True
second.start()
third = threading.Thread(target=grab_ip, args=("http://ifconfig.me/ip", ip_queue))
third.daemon = True
third.start()
fourth = threading.Thread(target=grab_ip, args=("http://corz.org/ip/", ip_queue))
fourth.daemon = True
fourth.start()
# These two queue get requests basically wait for the threads above to return results and then I move the main thread to conclusion.
firstIP = ip_queue.get()
secondIP = ip_queue.get()
# I am assuming these IP addresses are the same for the sake of this problem, but who knows, they could be different...
print firstIP
# Lets go ahead and quit as soon as we've printed the IP to the command line
sys.exit(0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment