I have a python class which grabs the IP address of the local machine you are on. It works on actual hardware (unless it's MacOS with bridged devices involved), or local VMs. This is the code:
class IPAddress:
ip_address = None
def __init__(self):
return
def _get_interface_ip(self,ifname):
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
return socket.inet_ntoa(fcntl.ioctl(s.fileno(), 0x8915, struct.pack('256s',
ifname[:15]))[20:24])
# does not work on MacOS with bridged devices such as vboxnet0, tap0, tun0
def get_lan_ip(self):
hostname = socket.gethostname()
ip = u''
try:
ip = socket.gethostbyname(hostname)
except socket.gaierror, e:
try:
ip = socket.gethostbyname(u'localhost')
except: pass
if ip.startswith("127.") and os.name != "nt":
interfaces = [
"eth0",
"eth1",
"eth2",
"en0",
"en1",
"en2",
"wlan0",
"wlan1",
"wifi0",
"ath0",
"ath1",
"ppp0",
]
for ifname in interfaces:
try:
ip = self._get_interface_ip(ifname)
break
except IOError:
pass
return ip
# Find out this instance
x = IPAddress()
server_ip = x.get_lan_ip()
This works everywhere it seems except on AWS. On AWS ifconfig eth0 gives the internal IP address assigned to eth0, whereas the class gives the external CNAME'd IP address associated with accessing the instance (in EC2 Classic).
What gives? Is there a better way to do self discovery with (for example) boto?