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())
'192.168.20.200'
>>> socket.gethostbyaddr(socket.gethostname())
('bigServer', [], ['192.168.20.200'])
>>> socket.gethostbyname_ex(socket.gethostname())
('bigServer.mydomain.com', [], ['192.168.20.200', '192.168.1.41'])
>>>
>>> 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.")
'192.168.1.41'
>>> getIpAddrForSubnet("192.168.20.")
'192.168.20.200'

Labels: ,

0 Comments:

Post a Comment

<< Home