Find interface associated with default route?
Neal Becker
ndbecker2 at gmail.com
Sun Nov 12 08:24:48 EST 2006
Neal Becker wrote:
> Fredrik Lundh wrote:
>
>> Neal Becker wrote:
>>
>>> Any thoughts on howto find the interface associated with the default
>>> route (this is on linux)?
>>
>> are you sure you sent this to the right newsgroup ?
>>
>> is this what you want ?
>>
>> >>> import os
>> >>> for line in os.popen("/sbin/route"):
>> ... line = line.split()
>> ... if line[0] == "default":
>> ... print line[-1]
>> ...
>> eth0
>>
>
> Well, I was hoping for something more 'elegant' - meaning relying on
> library
> calls rather than calling programs. Obviously, /sbin/route has some
> library calls to obtain this info, and maybe python has a wrapper for it.
>
> Yes, this is the right group - I want a python solution.
>
A quick strace reveals that 'route' just reads /proc/net/route, so:
def get_default_if():
f = open ('/proc/net/route', 'r')
for line in f:
words = string.split (line)
dest = words[1]
try:
if (int (dest) == 0):
interf = words[0]
break
except ValueError:
pass
return interf
More information about the Python-list
mailing list