Find interface associated with default route?

Giovanni Bajo noway at sorry.com
Sun Nov 12 19:05:08 EST 2006


Neal Becker wrote:

> 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

And if you acknowledge that /proc/net/route is a CSV file, you can be more
terse and clear:

>>> import csv
>>> def get_default_if():
...     f = open('/proc/net/route')
...     for i in csv.DictReader(f, delimiter="\t"):
...             if long(i['Destination'], 16) == 0:
...                     return i['Iface']
...     return None
...
>>>
>>> get_default_if()
'ppp0'

-- 
Giovanni Bajo





More information about the Python-list mailing list