free hit counter

Tuesday, May 25, 2010

finding IP addresses of all local adapters in Python

We've got an XmlRpcServer app written in Python, and when we wanted it to run on several different servers I thought I was being clever and rather than hardcode the IP address I'd just look it up; a quick search on the intertubes turned suggested:

serverIP= socket.gethostbyname(socket.gethostname())

This worked great on the original workstation we'd been running the script from, but when I put it on another machine it failed. Turns out, that machine has two network adapters, and you need to call the gethostbyname_ex() version (which the python docs don't have much to say about). That version of the call returns a list with all the adapters, and you need to search through them for the one you want. this is how I did it:

Python 2.5.2 (r252:60911, Dec 2 2008, 09:26:14)
[GCC 3.4.4 (cygming special, gdc 0.12, using dmd 0.125)] on cygwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import socket
>>> socket.gethostbyname(socket.gethostname())
>>> socket.gethostbyaddr(socket.gethostname())
('bigServer', [], [''])
>>> socket.gethostbyname_ex(socket.gethostname())
('', [], ['', ''])
>>> def getIpAddrForSubnet(subnetStr):
... ipAddrs= socket.gethostbyname_ex(socket.gethostname())
... for value in ipAddrs[2]:
... if str(value).find(subnetStr) >= 0: return value
>>> getIpAddrForSubnet("192.168.1.")
>>> getIpAddrForSubnet("192.168.20.")

Labels: ,


Post a Comment

<< Home