How to get the ip addresses of a nic

Bo Jacobsen bo at systemhouse.dk
Wed Apr 21 18:18:34 EDT 2004


> > Is there a simple way to get all the ip addresses of a nic, beyound
parsing
> > /etc/sysconfig/.....
> >
> > -------------------------------------------------
> > Bo Jacobsen
> >
> >
>
> I just had to do deal with this BS a couple days ago.  I couldn't get
> the socket module to give it to me.  The only ways I found were parsing
> the output of ifconfig (or equivalent on other platforms) or connecting
> to server and then looking at your socket.  I don't like either one.
>
> Rob
>
> # Method 1
>
> s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
> s.connect(('somewebserver', 80))
> return s.getsockname()[0]
>
> # Method 2
>
> if sys.platform == 'linux2':
>      out = commands.getoutput('/sbin/ifconfig')
>      return re.search('inet addr:(.+?)\s', out).group(1)
> elif sys.platform == 'win32':
>      si, so = os.popen4('route print')
>      out = so.read()
>      ipPatt = r'\d+\.\d+\.\d+.\d+'
>      return re.search(r'0\.0\.0\.0\s+0\.0\.0\.0\s+' + ipPatt + r'\s+(' +
> ipPatt + ')', out).group(1)
> elif sys.platform == 'freebsd5':
>      out = commands.getoutput('/sbin/ifconfig')
>      return re.search('inet (\S+)\s', out).group(1)
> else:
>      raise Exception('unsupported platform: %s' % sys.platform)

And the parsing gets much more difficult with multiple nics and aliases.

Bo





More information about the Python-list mailing list