#!/usr/bin/env python

# Python script for printing both the internal IP and the external IP of your
# Mac: these two IPs might be different if you are behind a router or a NAT
# device.
# Source: http://www.cs.cmu.edu/~benhdj/Mac/unix.html#getIP
# Modified by me (GZ, Oct 2006)

import urllib, re, sys, os

# if this changes we need to revise the code to get the external IP
ip_telling_url = 'http://www.dyndns.org/cgi-bin/check_ip.cgi'

# get the external IP
mo = re.search(r'\d+\.\d+\.\d+\.\d+', urllib.urlopen(ip_telling_url).read())
if mo:
	print 'External IP          : ', mo.group()
else:
	print 'Cannot get the external IP!'

# get the internal IP of an interface
for targetInt in ("en0", "en1"):
	output = os.popen('ipconfig getifaddr %s 2>&1' % targetInt).read().strip()
	if re.match(r'.*failed', output):
		continue
	if re.match(r'\d+\.\d+\.\d+\.\d+', output):
		print 'Internal IP for ', targetInt, ': ', output
	else:
		print 'Cannot get the internal IP for interface \'%s\'' % targetInt

# Bug: we could actually check with 'ifconfig' which interface is active

