Location Script
On my sidebar is the "Where is Josh" box. This explains how it's done.
I have a DynDNS.org account with several hostnames in it. One is the CelloFellow.HomeLinux.net site that you are viewing and runs on my home server. Another is cellofellow.is-a-geek.org, which points to my laptop.
My script runs a DNS lookup on both the home and my laptop hostnames. If they are the same, then I'm at home. I also generate a list of all IP addresses in my university's subnet. If my IP address is in that list, then I'm at school. If it's neither, I'm somewhere else.
It's implemented as a python CGI script that returns data in various formats, including JSON. I have a little bit of jQuery JavaScript on my site that loads this JSON data and displays it.
Not perfect, as there'll be a delay as the DNS records change and I may be offline and somewhere else but it still say I'm at school for example. Still, rather fun.
Python Code
Here is the python code for the script.
#!/usr/bin/env python
from socket import gethostbyname
import os, subprocess
import simplejson
# Get IP addresses of hostnames.
try:
myip = gethostbyname('cellofellow.is-a-geek.org')
homeip = gethostbyname('cellofellow.homelinux.net')
except:
exit("Can't find hostnames. Network probably not working.")
# Get all IP addresses in Weber State's subnet.
schoolsubnetprefixes = [ '137.190.%d.' % x for x in range(208, 212) ]
schoolsubnet = [ prefix + str(x)
for prefix in schoolsubnetprefixes
for x in range(255)
]
del schoolsubnetprefixes
# If laptop and home IPs are the same, I'm at home.
isAtHome = myip == homeip
# If laptop IP is in Weber's subnet, I'm at school.
isAtSchool = myip in schoolsubnet
# Function that formats the output according to the previously set variables.
def place(format='str'):
if format=='json':
return simplejson.dumps({
'location': place('str'),
'known': place('bool'),
'ip': myip,
})
elif format=='bool':
return isAtHome or isAtSchool
if isAtHome:
if format=='str':
return "Josh is at home."
elif format=='int':
return 1
elif isAtSchool:
if format=='str':
return "Josh is at school."
elif format=='int':
return 2
else:
if format=='str':
return "Don't know where Josh is."
elif format=='int':
return 0
# This is ran if being run as a CGI script.
def main():
import cgi
form = cgi.FieldStorage()
format = form.getvalue('fmt') or 'str'
mimetype = 'text/plain'
if format == 'json': mimetype = 'application/json'
print "Content-Type: %s\n" % mimetype
print place(format)
if __name__=='__main__': main()