Python: get default gateway for a local interface/ip address in linux

后端 未结 8 1726
礼貌的吻别
礼貌的吻别 2020-12-06 01:09

On Linux, how can I find the default gateway for a local ip address/interface using python?

I saw the question \"How to get internal IP, external IP and default gate

8条回答
  •  情书的邮戳
    2020-12-06 01:38

    For completeness (and to expand on alastair's answer), here is an example that uses "netifaces" (tested under Ubuntu 10.04, but this should be portable):

    $ sudo easy_install netifaces
    Python 2.6.5 (r265:79063, Oct  1 2012, 22:04:36)
    ...
    $ ipython
    ...
    In [8]: import netifaces
    In [9]: gws=netifaces.gateways()
    In [10]: gws
    Out[10]:
    {2: [('192.168.0.254', 'eth0', True)],
     'default': {2: ('192.168.0.254', 'eth0')}}
    In [11]: gws['default'][netifaces.AF_INET][0]
    Out[11]: '192.168.0.254'
    

    Documentation for 'netifaces': https://pypi.python.org/pypi/netifaces/

提交回复
热议问题