2010-05-03 61 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()