2010-05-03 59 views
11

在Linux上,如何使用python找到本地IP地址/接口的默認網關?Python:在Linux中獲取本地接口/ IP地址的默認網關

我看到了問題:「如何獲得內部IP,外部IP和默認網關的UPnP」,但接受的解決方案只顯示如何獲得Windows上的網絡接口的本地IP地址。

謝謝。

+0

你可以使用python執行系統的'route'命令,然後處理輸出以獲取默認網關。也可能有一個路線標誌只打印。我不知道python的方式atm。祝你好運。 – 2010-05-03 23:24:15

回答

21

對於誰不想要一個額外的依賴,不喜歡調用子過程的人,這裏是你怎麼做你自己通過閱讀/proc/net/route直接:

import socket, struct 

def get_default_gateway_linux(): 
    """Read the default gateway directly from /proc.""" 
    with open("/proc/net/route") as fh: 
     for line in fh: 
      fields = line.strip().split() 
      if fields[1] != '00000000' or not int(fields[3], 16) & 2: 
       continue 

      return socket.inet_ntoa(struct.pack("<L", int(fields[2], 16))) 

我沒有因此我不確定字節序是否依賴於處理器體系結構,但如果是,請將struct.pack('<L', ...中的<替換爲=,以便代碼使用機器的本地字節序。

5

看來http://pypi.python.org/pypi/pynetinfo/0.1.9可以做到這一點,但我沒有測試過它。

+1

這個庫很棒! 它有一個netinfo.get_routes方法,它返回一個包含我需要的數據的字典的元組。 謝謝! – GnP 2010-05-04 00:07:22

0
def get_ip(): 
    file=os.popen("ifconfig | grep 'addr:'") 
    data=file.read() 
    file.close() 
    bits=data.strip().split('\n') 
    addresses=[] 
    for bit in bits: 
     if bit.strip().startswith("inet "): 
      other_bits=bit.replace(':', ' ').strip().split(' ') 
      for obit in other_bits: 
       if (obit.count('.')==3): 
        if not obit.startswith("127."): 
         addresses.append(obit) 
        break 
    return addresses 
3

netifaces的最新版本也可以這樣做,但不像pynetinfo,它將在比Linux(包括Windows,OS X,FreeBSD和Solaris)上其他系統的正常工作。

9

爲了完整(並擴大阿拉斯泰爾的答案),這裏是使用「netifaces」的一個例子(Ubuntu的10.04下進行測試,但是這應該是便攜式):

爲「netifaces」
$ 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' 

文檔: https://pypi.python.org/pypi/netifaces/

+0

這適用於osx!感謝堆! – 2017-09-27 21:12:32

-1

你可以像這樣(測試使用Python 2.7和Mac OS X Capitain但應在GNU/Linux的工作太): 進口子

def system_call(command): 
    p = subprocess.Popen([command], stdout=subprocess.PIPE, shell=True) 
    return p.stdout.read() 


def get_gateway_address(): 
    return system_call("route -n get default | grep 'gateway' | awk '{print $2}'") 

print get_gateway_address()