Skip to content

Instantly share code, notes, and snippets.

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:
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(['', 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:,+%s' % (latitude, longitude)
except getopt.GetoptError, err:
except socket.herror, err:
print str(err)
if __name__ == '__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.