Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Get location based on IP address.
#!/usr/bin/env python
import getopt
import urllib
import socket
def usage(name):
print 'Usage: %s -i IP' % name
print 'Usage: %s -h hostname' % name
def main(argv=sys.argv):
if len(argv) < 3:
usage(argv[0])
sys.exit(0)
try:
opts, args = getopt.getopt(argv[1:], 'i:h:', ['ip=', 'hostname='])
for o, a in opts:
if o == '-i':
ipaddr = a
hostname = socket.gethostbyaddr(a)[0]
elif o == '-h':
hostname = a
ipaddr = socket.gethostbyname(a)
print 'Hostname:', hostname
print 'IP address:', ipaddr
url = ''.join(['http://api.hostip.info/get_html.php?ip=', ipaddr, '&position=true'])
f = urllib.urlopen(url)
result = f.readlines()
for line in result:
if line != '\n':
print line.strip()
if line.lower().startswith('longitude'):
longitude = line.split(':')[1].strip()
if line.lower().startswith('latitude'):
latitude = line.split(':')[1].strip()
print 'Google map: http://maps.google.com/maps?q=%s,+%s' % (latitude, longitude)
except getopt.GetoptError, err:
usage(argv[0])
except socket.herror, err:
print str(err)
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.