1

I want determine the ip of my router address by writing a python code. I found this proposal:

$ 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'

and my result in the terminal:

In [1]: import netifaces

In [2]: gws=netifaces.gateways()

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)

/home/rimeh/Bureau/<ipython-input-2-47b29e25a9b8> in <module>()
----> 1 gws=netifaces.gateways()

AttributeError: 'module' object has no attribute 'gateways'

How can help me please, I need help. thanks.

kaio
  • 677

1 Answers1

3
  1. Install netifaces using pip:

    sudo apt-get install python-pip
    sudo apt-get build-dep python-netifaces
    sudo pip install netifaces
    
  2. To get the gateway ip you can use the following code:

    $ python 
    Python 2.7.6 (default, Mar 22 2014, 22:59:56) 
    [GCC 4.8.2] on linux2
    Type "help", "copyright", "credits" or "license" for more information.
    >>> import netifaces
    >>> gws=netifaces.gateways()
    >>> gws['default'].values()[0][0]
    '192.168.1.1'
    >>> 
    
  • netifaces has packages available: http://packages.ubuntu.com/search?suite=trusty&arch=any&mode=filename&searchon=contents&keywords=netifaces – muru Mar 09 '15 at 22:31
  • 1
    @muru thanks, I know but you need at least netifaces 0.10.0 to call gateways() (See https://pypi.python.org/pypi/netifaces) – Sylvain Pineau Mar 09 '15 at 22:35
  • @SylvainPineau, I did the 1 but I have the same problem: rimeh@rimeh-PC:~$ python Python 2.7.3 (default, Dec 18 2014, 19:10:20) [GCC 4.6.3] on linux2 Type "help", "copyright", "credits" or "license" for more information.

    import netifaces gws=netifaces.gateways() Traceback (most recent call last): File "", line 1, in AttributeError: 'module' object has no attribute 'gateways'

    – kaio Mar 10 '15 at 09:24
  • @muru I installed netifaces but the same problem. – kaio Mar 10 '15 at 09:59