ip address?
Peter Hansen
peter at engcorp.com
Sat Jan 26 13:50:39 EST 2002
Jason Orendorff wrote:
>
> Emile van Sebille writes:
> > >>> import os
> > >>> ipaddr = [ i for i in os.popen('route print').readlines()
> > if i.split()[0] == '0.0.0.0' ][0].split()[3]
>
> ...where ordinary humans would write something awful like...
>
> import os
>
> def get_address():
> f = os.popen('route print', 'r')
> lines = f.readlines()
> f.close()
>
> for line in lines:
> fields = line.split()
> if fields[0] == '0.0.0.0':
> return fields[3]
> raise Exception, 'no routes found'
This finds the interface for the first default gateway.
Although it's probably an error, multiple default
gateways might be configured (especially when people
have dial-up connections which are configured wrong,
or VPN adapters). And when this happens, I believe
Windows takes the *last* of the default gateways listed.
(Or maybe it uses the cost metric to decide which to
use, although maybe they can be the same...)
More information about the Python-list
mailing list