Last active
December 2, 2021 16:17
-
-
Save superkojiman/10912004 to your computer and use it in GitHub Desktop.
Get location based on IP address.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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