Code Monkey home page Code Monkey logo

netifaces's Introduction

netifaces 0.10.8

Linux/macOS Build Status (Linux/Mac)
Windows Build Status (Windows)

Warning

netifaces needs a new maintainer. al45tair is no longer able to maintain it or make new releases due to work commitments.

1. What is this?

It's been annoying me for some time that there's no easy way to get the address(es) of the machine's network interfaces from Python. There is a good reason for this difficulty, which is that it is virtually impossible to do so in a portable manner. However, it seems to me that there should be a package you can easy_install that will take care of working out the details of doing so on the machine you're using, then you can get on with writing Python code without concerning yourself with the nitty gritty of system-dependent low-level networking APIs.

This package attempts to solve that problem.

2. How do I use it?

First you need to install it, which you can do by typing:

tar xvzf netifaces-0.10.8.tar.gz
cd netifaces-0.10.8
python setup.py install

Note that you will need the relevant developer tools for your platform, as netifaces is written in C and installing this way will compile the extension.

Once that's done, you'll need to start Python and do something like the following:

>>> import netifaces

Then if you enter

>>> netifaces.interfaces()
['lo0', 'gif0', 'stf0', 'en0', 'en1', 'fw0']

you'll see the list of interface identifiers for your machine.

You can ask for the addresses of a particular interface by doing

>>> netifaces.ifaddresses('lo0')
{18: [{'addr': ''}], 2: [{'peer': '127.0.0.1', 'netmask': '255.0.0.0', 'addr': '127.0.0.1'}], 30: [{'peer': '::1', 'netmask': 'ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff', 'addr': '::1'}, {'peer': '', 'netmask': 'ffff:ffff:ffff:ffff::', 'addr': 'fe80::1%lo0'}]}

Hmmmm. That result looks a bit cryptic; let's break it apart and explain what each piece means. It returned a dictionary, so let's look there first:

{ 18: [...], 2: [...], 30: [...] }

Each of the numbers refers to a particular address family. In this case, we have three address families listed; on my system, 18 is AF_LINK (which means the link layer interface, e.g. Ethernet), 2 is AF_INET (normal Internet addresses), and 30 is AF_INET6 (IPv6).

But wait! Don't use these numbers in your code. The numeric values here are system dependent; fortunately, I thought of that when writing netifaces, so the module declares a range of values that you might need. e.g.

>>> netifaces.AF_LINK
18

Again, on your system, the number may be different.

So, what we've established is that the dictionary that's returned has one entry for each address family for which this interface has an address. Let's take a look at the AF_INET addresses now:

>>> addrs = netifaces.ifaddresses('lo0')
>>> addrs[netifaces.AF_INET]
[{'peer': '127.0.0.1', 'netmask': '255.0.0.0', 'addr': '127.0.0.1'}]

You might be wondering why this value is a list. The reason is that it's possible for an interface to have more than one address, even within the same family. I'll say that again: you can have more than one address of the same type associated with each interface.

Asking for "the" address of a particular interface doesn't make sense.

Right, so, we can see that this particular interface only has one address, and, because it's a loopback interface, it's point-to-point and therefore has a peer address rather than a broadcast address.

Let's look at a more interesting interface.

>>> addrs = netifaces.ifaddresses('en0')
>>> addrs[netifaces.AF_INET]
[{'broadcast': '10.15.255.255', 'netmask': '255.240.0.0', 'addr': '10.0.1.4'}, {'broadcast': '192.168.0.255', 'addr': '192.168.0.47'}]

This interface has two addresses (see, I told you...) Both of them are regular IPv4 addresses, although in one case the netmask has been changed from its default. The netmask may not appear on your system if it's set to the default for the address range.

Because this interface isn't point-to-point, it also has broadcast addresses.

Now, say we want, instead of the IP addresses, to get the MAC address; that is, the hardware address of the Ethernet adapter running this interface. We can do

>>> addrs[netifaces.AF_LINK]
[{'addr': '00:12:34:56:78:9a'}]

Note that this may not be available on platforms without getifaddrs(), unless they happen to implement SIOCGIFHWADDR. Note also that you just get the address; it's unlikely that you'll see anything else with an AF_LINK address. Oh, and don't assume that all AF_LINK addresses are Ethernet; you might, for instance, be on a Mac, in which case:

>>> addrs = netifaces.ifaddresses('fw0')
>>> addrs[netifaces.AF_LINK]
[{'addr': '00:12:34:56:78:9a:bc:de'}]

No, that isn't an exceptionally long Ethernet MAC address---it's a FireWire address.

As of version 0.10.0, you can also obtain a list of gateways on your machine:

>>> netifaces.gateways()
{2: [('10.0.1.1', 'en0', True), ('10.2.1.1', 'en1', False)], 30: [('fe80::1', 'en0', True)], 'default': { 2: ('10.0.1.1', 'en0'), 30: ('fe80::1', 'en0') }}

This dictionary is keyed on address family---in this case, AF_INET---and each entry is a list of gateways as (address, interface, is_default) tuples. Notice that here we have two separate gateways for IPv4 (AF_INET); some operating systems support configurations like this and can either route packets based on their source, or based on administratively configured routing tables.

For convenience, we also allow you to index the dictionary with the special value 'default', which returns a dictionary mapping address families to the default gateway in each case. Thus you can get the default IPv4 gateway with

>>> gws = netifaces.gateways()
>>> gws['default'][netifaces.AF_INET]
('10.0.1.1', 'en0')

Do note that there may be no default gateway for any given address family; this is currently very common for IPv6 and much less common for IPv4 but it can happen even for AF_INET.

BTW, if you're trying to configure your machine to have multiple gateways for the same address family, it's a very good idea to check the documentation for your operating system very carefully, as some systems become extremely confused or route packets in a non-obvious manner.

I'm very interested in hearing from anyone (on any platform) for whom the gateways() method doesn't produce the expected results. It's quite complicated extracting this information from the operating system (whichever operating system we're talking about), and so I expect there's at least one system out there where this just won't work.

3. This is great! What platforms does it work on?

It gets regular testing on OS X, Linux and Windows. It has also been used successfully on Solaris, and it's expected to work properly on other UNIX-like systems as well. If you are running something that is not supported, and wish to contribute a patch, please use Github to send a pull request.

4. What license is this under?

It's an MIT-style license. See LICENSE.

5. Why the jump to 0.10.0?

Because someone released a fork of netifaces with the version 0.9.0. Hopefully skipping the version number should remove any confusion. In addition starting with 0.10.0 Python 3 is now supported and other features/bugfixes have been included as well. See the CHANGELOG for a more complete list of changes.

netifaces's People

Contributors

al45tair avatar asomers avatar chugcup avatar doug-horn avatar harshalbarefoot avatar hugovk avatar jlaine avatar lambdalisue avatar martinbasti avatar methane avatar mrakitin avatar opalmer avatar pabelanger avatar pcmanticore avatar rajendra-dendukuri avatar rtobar avatar sajith avatar skorokithakis avatar steffann avatar tsibley avatar yuri-sevatz avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

netifaces's Issues

cross compilation steps

I am not sure I should call this as issue or not. Please close if this doesn't fit in the issue category.
It would be helpful if cross compilation steps are provided in the README. Or better if autoconf/makefile kind support available for cross compilation.

adding QNX support

I cross compiled netifaces for QNX. I had to patch the setup.py file and I was wondering if you would be interested in adding a patch to the code to allow it to build for QNX

May Anyone tell me how do i fix this error?

I have VS Studio 2019 and build tools 2019 but i can't still build it, I can't find any proper VS Studio 14 Build Tools Bcz of 2019 replacing stuff So Please tell me how do I fix this Build Error.

image

ModuleNotFoundError: No module named 'netifaces'

Hi,
The both pip install and download , unzip and pyhton setup.py install methods do not seem to be correctly install with windows 10 python 3.6.

The error is: "import netifaces, ModuleNotFoundError: No module named 'netifaces'."

I am no expert, but the issue looks like no "netifaces" directory is in the site package area. the pip install netifaces seems to yeild the same results, not copied here.

The log for the downlad and python setup.py install method is:
C:\netifaces-master\netifaces-master>python setup.py install
running install
running bdist_egg
running egg_info
writing netifaces.egg-info\PKG-INFO
writing dependency_links to netifaces.egg-info\dependency_links.txt
writing top-level names to netifaces.egg-info\top_level.txt
reading manifest file 'netifaces.egg-info\SOURCES.txt'
writing manifest file 'netifaces.egg-info\SOURCES.txt'
installing library code to build\bdist.win32\egg
running install_lib
running build_ext
creating build\bdist.win32\egg
copying build\lib.win32-3.6\netifaces.cp36-win32.pyd -> build\bdist.win32\egg
creating stub loader for netifaces.cp36-win32.pyd
byte-compiling build\bdist.win32\egg\netifaces.py to netifaces.cpython-36.pyc
creating build\bdist.win32\egg\EGG-INFO
copying netifaces.egg-info\PKG-INFO -> build\bdist.win32\egg\EGG-INFO
copying netifaces.egg-info\SOURCES.txt -> build\bdist.win32\egg\EGG-INFO
copying netifaces.egg-info\dependency_links.txt -> build\bdist.win32\egg\EGG-INFO
copying netifaces.egg-info\top_level.txt -> build\bdist.win32\egg\EGG-INFO
copying netifaces.egg-info\zip-safe -> build\bdist.win32\egg\EGG-INFO
writing build\bdist.win32\egg\EGG-INFO\native_libs.txt
creating 'dist\netifaces-0.10.7-py3.6-win32.egg' and adding 'build\bdist.win32\egg' to it
removing 'build\bdist.win32\egg' (and everything under it)
Processing netifaces-0.10.7-py3.6-win32.egg
Removing c:\users\joe\appdata\local\programs\python\python36-32\lib\site-packages\netifaces-0.10.7-py3.6-win32.egg
Copying netifaces-0.10.7-py3.6-win32.egg to c:\users\joe\appdata\local\programs\python\python36-32\lib\site-packages
netifaces 0.10.7 is already the active version in easy-install.pth

Installed c:\users\joe\appdata\local\programs\python\python36-32\lib\site-packages\netifaces-0.10.7-py3.6-win32.egg
Processing dependencies for netifaces==0.10.7
Finished processing dependencies for netifaces==0.10.7

C:\netifaces-master\netifaces-master>

The directory shows:
C:\Users\Joe\AppData\Local\Programs\Python\Python36-32\Lib\site-packages>dir n*
Directory of C:\Users\Joe\AppData\Local\Programs\Python\Python36-32\Lib\site-packages

08/04/2018 11:40 PM 14,849 netifaces-0.10.7-py3.6-win32.egg
07/31/2018 06:22 PM

networkx
07/31/2018 06:22 PM networkx-2.1-py3.6.egg-info
08/02/2018 09:33 PM numpy
08/02/2018 09:33 PM numpy-1.15.0.dist-info
1 File(s) 14,849 bytes
4 Dir(s) 731,734,827,008 bytes free

C:\Users\Joe\AppData\Local\Programs\Python\Python36-32\Lib\site-packages>

Thanks for any help you can offer

netifaces.c:210:6: error: #error You need to add code for your platform.

Hi,
trying to install from 10.09.tar offline on AWS EC2 instance with RHEL 7.6.5 and cannot get it installed. Could you give me a hint where to debug this?

Further error is:

error You need to add code for your platform.

  ^

netifaces.c: In function ‘gateways’:
netifaces.c:1466:22: warning: unused variable ‘defaults’ [-Wunused-variable]
PyObject *result, *defaults;
^
netifaces.c: At top level:
netifaces.c:438:1: warning: ‘string_from_netmask’ defined but not used [-Wunused-function]
string_from_netmask (struct sockaddr *addr,
^
netifaces.c:689:1: warning: ‘add_to_family’ defined but not used [-Wunused-function]
add_to_family (PyObject *result, int family, PyObject *obj)
^
error: command 'gcc' failed with exit status 1

Thanks in advance

netifaces.gateways() does not work in a Windows CYGWIN environment

While netifaces.interfaces() and netifaces.ifaddresses(<iface>) appear to work fine in a CYGWIN environment running on Windows 7, netifaces.gateways() does not.

The openstack command line client uses this library to determine whether IPv6 is locally supported. When the netifaces.gateways() method is executed by the openstack client, an error is thrown which the client is unprepared to gracefully handle and instead simply aborts (I've worked around this problem by skipping the "IPv6 supported" check in the openstack client, since I'm not using IPv6 yet.)

I do not have the expertise to fix netifaces.gateways() on CYGWIN myself, but I'd be willing to test any proposed solutions.

Here's a copy of the netifaces.gateways() run manually:

$ python
Python 3.6.4 (default, Jan  7 2018, 15:53:53)
[GCC 6.4.0] on cygwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import netifaces
>>> netifaces.gateways()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
OSError: Unable to obtain gateway information on your platform.
>>> 

is "pip install netifaces" supported?

I tried the following in my python venv on MacOS:

pip install netifaces

The installation itself was successful, but I was not able to do import netifaces in my python code. Did I missing anything? This is on Mac OS X.

Attaching the log of pip install:

$ pip install netifaces
Collecting netifaces
  Downloading https://files.pythonhosted.org/packages/7f/ac/fab3113cbe9c42bdd06735b6b7e0d37816f97eb3d744049d16f3a3b3d9b7/netifaces-0.10.9-cp37-cp37m-macosx_10_14_x86_64.whl
Installing collected packages: netifaces
Successfully installed netifaces-0.10.9

Type of interface?

I'd like to be able to loop through netifaces.interfaces() and get only the ones that are ethernet, or bluetooth, wifi. Is there a way to do this currently? If not, is it planned?

EDIT: netifaces.ifaddresses().keys() gives me dict_keys([17, 2, 10]) for both ethernet and wifi, but loopback is just dict_keys([17])
Which is why I was curious if I was missing something.

interfaces() is quadratic

https://github.com/al45tair/netifaces/blob/master/netifaces.c#L1359

  for (addr = addrs; addr; addr = addr->ifa_next) {
    if (!prev_name || strncmp (addr->ifa_name, prev_name, IFNAMSIZ) != 0) {
      PyObject *ifname = PyUnicode_FromString (addr->ifa_name);
    
      if (!PySequence_Contains (result, ifname))
        PyList_Append (result, ifname);
      Py_DECREF (ifname);
      prev_name = addr->ifa_name;
    }
  }

PySequence_Contains is being called inside a loop over all the addresses; it's O(n) which makes this loop O(n^2). This really hurts in a virtualization context with hundreds of interfaces.

Improper mac detection?

These give me proper mac addresses for the wireless card:

  • ip link set <insert_wireless_interface_here> down
  • Being connected to a wireless network

This gives me a mac address that isn't on any of my hardware:

  • Disconnecting from a wireless network ( NOT disabling wireless ) and running:
import netifaces

for each in netifaces.interfaces():
    try:
        print(each)
        print(netifaces.ifaddresses(each))
    except KeyError:
        pass

The wireless has a totally different mac address. Why?

EDIT: This is on Debian 9 and happened with the latest ( 0.10.7 ) and the apt version ( 0.10.4 )
Though both versions give a different wrong mac address ( 46:4a:22:e1:1e:01 for the 0.10.7 version, and 7e:3d:73:92:94:6e for the 0.10.4 version )

EDIT2: Output of the above command while using 0.10.7 via pip:

lo
{17: [{'addr': '00:00:00:00:00:00', 'peer': '00:00:00:00:00:00'}], 2: [{'netmask': '255.0.0.0', 'addr': '127.0.0.1', 'peer': '127.0.0.1'}], 10: [{'netmask': 'ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff/128', 'addr': '::1'}]}
enp7s0
{17: [{'broadcast': 'ff:ff:ff:ff:ff:ff', 'addr': '14:18:77:c7:c6:38'}]}
wlp6s0
{17: [{'broadcast': 'ff:ff:ff:ff:ff:ff', 'addr': '46:4a:22:e1:1e:01'}]}

Dupliacate of #65 - please ignore [10.9] netifaces.ifaddresses() on AF_NET6 returns CIDR with v6 netmask

Hi,

Can someone please confirm if there is a regression between python-netifaces-0.10.4 and python3-netifaces-0.10.9 where
netifaces.ifaddresses() on AF_NET6 returns the v6 netmask entry with a the CIDR. Is this by design, and if so why is it
not consistent with AF_NET for the v4 netmasks?

Changed behavior seen for AF_INET6 in python3-netifaces-0.10.9
Python 3.6.8 (default, Dec 5 2019, 15:45:45)
[GCC 8.3.1 20191121 (Red Hat 8.3.1-5)] on linux
Type "help", "copyright", "credits" or "license" for more information.

import netifaces
netifaces.ifaddresses('br_mgmt')[netifaces.AF_INET6][0].get('netmask')
'ffff:ffff:ffff:ffff::/64'
netifaces.ifaddresses('br_mgmt')[netifaces.AF_INET][0].get('netmask')
'255.255.255.0'

Behavior seen for AF_INET6 in python-netifaces-0.10.4
Python 2.7.5 (default, Feb 26 2020, 04:21:27)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-36)] on linux2
Type "help", "copyright", "credits" or "license" for more information.

import netifaces
netifaces.ifaddresses('br_mgmt')[netifaces.AF_INET6][0].get('netmask')
'ffff:ffff:ffff:ffff::'
netifaces.ifaddresses('br_mgmt')[netifaces.AF_INET][0].get('netmask')
'255.255.255.0'

Would appreciate if someone can please confirm if this is expected and the inconsistency between v4 and v6 in the netifaces 10.9 version.

Thanks,
Sharmin

Python 2.7 linux wheels are broken

The Python 2.7 wheels for Linux are broken and fail to import with undefined symbol: PyUnicodeUCS2_FromString. The cp27mu should be a wide unicode builds with PyUnicodeUCS4_*, but the extension module uses PyUnicodeUCS2_FromString. This breaks literally any Linux distribution that compiles Python 2.7 with UCS4 (Debian, Fedora, ...).

$ virtualenv-2.7 venv
New python executable in /tmp/venv/bin/python2
Also creating executable in /tmp/venv/bin/python
Installing setuptools, pip, wheel...done.
$ venv/bin/pip install netifaces
Collecting netifaces
  Downloading netifaces-0.10.6-cp27-cp27mu-manylinux1_x86_64.whl
Installing collected packages: netifaces
Successfully installed netifaces-0.10.6
$ venv/bin/python
Python 2.7.14 (default, Jan 17 2018, 14:28:32) 
[GCC 7.2.1 20170915 (Red Hat 7.2.1-2)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import netifaces
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: /tmp/venv/lib/python2.7/site-packages/netifaces.so: undefined symbol: ImportError: /tmp/venv/lib/python2.7/site-packages/netifaces.so: undefined symbol: PyUnicodeUCS2_FromString
$ strings /usr/lib64/libpython2.7.so | egrep PyUnicodeUCS._FromString
PyUnicodeUCS4_FromString

netifaces.gateways()['default'] picks the interface with the highest metric

IP route is showing that tun0 (my VPN) has the lowest metric:

$  ip route list | grep default
default via 10.100.24.1 dev tun0 proto static metric 50 
default via 192.168.1.1 dev wlp3s0 proto dhcp metric 600 

but netifaces is saying that my WiFi is the default interface:

netifaces.gateways()['default']
{2: ('192.168.1.1', 'wlp3s0')}

Changed behavior for netifaces.ifaddresses AF_INET6 in **python3-netifaces-0.10.9**

Hi,

Can someone please confirm if there is a regression between python-netifaces-0.10.4 and python3-netifaces-0.10.9 where
netifaces.ifaddresses() on AF_NET6 returns the v6 netmask entry with a the CIDR. Is this by design, and if so why is it
not consistent with AF_NET for the v4 netmasks?

Changed behavior seen for AF_INET6  in **python3-netifaces-0.10.9**
Python 3.6.8 (default, Dec  5 2019, 15:45:45)
[GCC 8.3.1 20191121 (Red Hat 8.3.1-5)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import netifaces
>>> netifaces.ifaddresses('br_mgmt')[netifaces.AF_INET6][0].get('netmask')
'ffff:ffff:ffff:ffff::/64'
>>> netifaces.ifaddresses('br_mgmt')[netifaces.AF_INET][0].get('netmask')
'255.255.255.0'
Behavior seen for AF_INET6  in **python-netifaces-0.10.4**
Python 2.7.5 (default, Feb 26 2020, 04:21:27)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-36)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import netifaces
>>> netifaces.ifaddresses('br_mgmt')[netifaces.AF_INET6][0].get('netmask')
'ffff:ffff:ffff:ffff::'
>>> netifaces.ifaddresses('br_mgmt')[netifaces.AF_INET][0].get('netmask')
'255.255.255.0'

Would appreciate if someone can please confirm if this is expected and the inconsistency between v4 and v6 in the netifaces 10.9 version.

Thanks,
Sharmin

Enhancement : ifa_flags

Some addr->ifa_flags bits are used to determine broadcast/peer address type.
Other bits can be useful, like IFF_UP (interface is up).
Do you agree this is a good idea to expose them to Python side ?

netifaces is broken on MacOS pyenv python 3.7

After installing netifaces on python 3.7 on MacOS user may fail to import the module with an errorthat looks like:

$ pip3.7 install netifaces                                                                                                                                                                                                                                           Collecting netifaces
Installing collected packages: netifaces
Successfully installed netifaces-0.10.7
You are using pip version 10.0.1, however version 18.1 is available.
You should consider upgrading via the 'pip install --upgrade pip' command.

$ python3.7                                                                                                                                                                                                                                                          Python 3.7.1 (default, Nov 12 2018, 16:10:19)
[Clang 10.0.0 (clang-1000.11.45.5)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
INFO: platform(system:Darwin, processor:i386, machine:x86_64
WARNING: ipython not installed, fallinback to normal mode.
>>> import netifaces
>>> Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: dlopen(/Users/ssbarnea/.pyenv/versions/3.7.1/lib/python3.7/site-packages/netifaces.cpython-37m-darwin.so, 2): Symbol not found: _PyInt_FromLong
Referenced from: /Users/ssbarnea/.pyenv/versions/3.7.1/lib/python3.7/site-packages/netifaces.cpython-37m-darwin.so
Expected in: flat namespace
in /Users/ssbarnea/.pyenv/versions/3.7.1/lib/python3.7/site-packages/netifaces.cpython-37m-darwin.so

I mention that this problem happens only with python-3.7.x, and other versions like 2.7, 3.5 or 3.6 do not have such problem.

I tried to reinstall (recompile) python but the failure is consistent.

See also:

how to find linux-mips-2.7/netifaces.o

I'm not experienced with python and try to install webthing from mozilla on a IoT device, thats why im asking for such strange arch support.
Is there any way to find a older or even any MIPS architecture compliled version?

Implement Continuous Integration on Travis and AppVeyor

Currently there's no automated build process for netifaces. While building netifaces is fairly simple it makes it harder for contributors to know if their code works without continuous integration . There's another reason for doing this however, it makes it really easy to build and release wheels for all platforms.

Building wheels and testing against new Python versions has come up multiple times before. Fixing this issue would be a great step forward:

Invalid errno check in netifaces.gateways()

At

} while (ret != 0 || errno == ENOMEM || errno == EINTR);
, gateways() will loop if the condition ret != 0 || errno == ENOMEM || errno == EINTR is true. However, that condition is invalid. If ret is 0, then errno is undefined. It may contain a value leftover from the caller of gateways, or it may contain an error that was internally handled by sysctl(3). Also, the fact that the very next line checks for negative values of ret implies that the condtion is wrong; as-is, ret can never be negative at that point. The condition should probably read ret != 0 && (errno == ENOMEM || errno == EINTR).

I think this is the root cause of iocage/iocage#766 .

ifaddresses doesn't return the netmask for VirtualBox interfaces

Python 2.7.9 (v2.7.9:648dcafa7e5f, Dec 10 2014, 10:10:46) 
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
>>> import netifaces
>>> netifaces.version
'0.10.7'
>>> netifaces.interfaces()
[u'lo0', u'gif0', u'stf0', u'en0', u'en1', u'en2', u'fw0', u'bridge0', u'p2p0', u'awdl0', u'utun0', u'utun1', u'utun2', u'vboxnet0', u'vboxnet1']
>>> netifaces.ifaddresses('vboxnet0')
{18: [{'addr': u'0a:00:27:00:00:00'}], 2: [{'broadcast': u'192.168.56.255', 'addr': u'192.168.56.1'}]}

But the netmask is specified for vboxnet0 interface:

host:~ user$ ifconfig vboxnet0
vboxnet0: flags=8943<UP,BROADCAST,RUNNING,PROMISC,SIMPLEX,MULTICAST> mtu 1500
        ether 0a:00:27:00:00:00 
        inet 192.168.56.1 netmask 0xffffff00 broadcast 192.168.56.255

vboxnet0 is Host-Only Adapter. I use VirtualBox version 5.0.30 r112061

packager's plea

Could you please make LICENSE, CHANGELOG and test.py part of pypi release tarball?

default gateway detection when using ECMP default route

Given the following working routing table with the default route being load balanced using ECMP and learned using BGP:

(netifaces)[root@host ~]# ip r
default proto bird src 10.139.128.11 
	nexthop via 172.16.104.68 dev eno50 weight 1 
	nexthop via 172.16.105.68 dev eno49 weight 1 
10.136.244.0/23 dev eno1 proto kernel scope link src 10.136.244.93 metric 100 
169.254.0.0/16 dev eno49 scope link metric 1005 
169.254.0.0/16 dev eno50 scope link metric 1007 
172.16.104.68/31 dev eno50 proto kernel scope link src 172.16.104.69 
172.16.105.68/31 dev eno49 proto kernel scope link src 172.16.105.69 

netifaces 0.10.6 fails to determine the gateway:

(netifaces)[root@host ~]# python
Python 2.7.5 (default, Aug  4 2017, 00:39:18) 
[GCC 4.8.5 20150623 (Red Hat 4.8.5-16)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import netifaces
>>> addr = netifaces.gateways()
>>> print addr
{'default': {}}
>>> 

Any chance of adding support for this? Thanks.

No wheels for Linux and Python 3.7

Went to install some dependencies and my pyenv sync was failing due to netifaces failing to build from source. Installing python3-devel allows me to work with it for now, but it would be nice to have Linux wheels for 3.7. Thanks!

KeyError on netifaces.AF_INET

When useing netifaces.AF_INET on a gre tunnel i get a key error.

*** KeyError: KeyError(2,)

Example:

gre_iface = netifaces.ifaddresses("dummy_gre")

print(gre_iface) ={17: [{'broadcast': 'ff:ff:ff:ff:ff:ff', 'addr': 'b2:22:6b:2f:63:3e'}], 10: [{'netmask': 'ffff:ffff:ffff:ffff::', 'addr': `'fe80::b022:6bff:fe2f:223e%dummy_gre'}]}

print(gre_iface[netifaces.AF_INET])
*** KeyError: KeyError(2,)

A gre interface.

1: dummy_gre@NONE: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1462 qdisc pfifo_fast master br_eth0 state UNKNOWN qlen 1000
    link/ether 12:d3:08:8e:33:d2 brd ff:ff:ff:ff:ff:ff
    inet6 fe80::10d3:8ff:fe8e:33d2/64 scope link 
       valid_lft forever preferred_lft forever

To create a gre tunnel/interface

ip link add <name_of_iface> type gretap remote <remote_ip_of_tunnel> ttl 255 local

My machine
CentOS Linux release 7.4.1708 (Core)
Linux l2lgw 3.10.0-862.2.3.el7.x86_64 #1 SMP Wed May 9 18:05:47 UTC 2018 x86_64 x86_64 x86_64 GNU/Linux

Note:
gre tunnels are have a fairly niche application so i doubt this is a priority just wanted to let people know. Nice project very handy keep up the good work.

windows10 netface names are not readable

In [1]: import netifaces

In [2]: add = netifaces.interfaces()

In [3]: add
Out[3]:
['{C7E350F7-D932-4BF2-9486-CD0EE8BAABA7}',
 '{D2CCEC51-24A8-496F-B8F9-27C9856B0782}',
 '{CE4B0FC2-0B6B-4950-BF26-31016C2FE4BA}',
 '{5CF3A1BA-924E-4BA0-B129-40F97985B17F}',
 '{D5265B1A-092F-42C7-8A8D-21DE7FE68F30}',
 '{CC12D0C5-3DC0-11EA-905F-806E6F6E6963}']

netmask is wrong on Windows 7 64bit

I got a wrong netmask which is set statically as 255.255.255.0 in adapter's properties dialog while it's 255.255.255.255 from netifaces.

>>> for i in netifaces.interfaces():
...     if netifaces.AF_INET in netifaces.ifaddresses(i):
...         for address in netifaces.ifaddresses(i)[netifaces.AF_INET]:
...             print(address)
...
{'addr': '192.168.3.100', 'netmask': '255.255.255.0', 'broadcast': '192.168.3.255'}
{'addr': '192.168.1.2', 'netmask': '255.255.255.255', 'broadcast': '192.168.1.2'}
{'addr': '127.0.0.1', 'netmask': '255.0.0.0', 'broadcast': '127.255.255.255'}

Wrong netmask for IPv6 address

Check netmask (67) displayed by ifconfig (which is right) and netmask (65) displayed by netifaces:

myterminal:~$ /sbin/ifconfig PortChannel1111
PortChannel1111: flags=4099<UP,BROADCAST,MULTICAST> mtu 9100
inet6 2001::1 prefixlen 64 scopeid 0x0
inet6 2001::2 prefixlen 65 scopeid 0x0
inet6 2001::3 prefixlen 67 scopeid 0x0 <-- ifconfig has correct value
ether 00:90:fb:5e:d6:ba txqueuelen 1000 (Ethernet)
RX packets 0 bytes 0 (0.0 B)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 0 bytes 0 (0.0 B)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0

myterminal:~$ python
Python 2.7.13 (default, Sep 26 2018, 18:42:22)
[GCC 6.3.0 20170516] on linux2
Type "help", "copyright", "credits" or "license" for more information.

import netifaces
netifaces.ifaddresses('PortChannel1111')
{17: [{'broadcast': u'ff:ff:ff:ff:ff:ff', 'addr': u'00:90:fb:5e:d6:ba'}], 10: [{'netmask': u'ffff:ffff:ffff:ffff:e000::/65', 'addr': u'2001::3'}, {'netmask': u'ffff:ffff:ffff:ffff:8000::/65', 'addr': u'2001::2'}, {'netmask': u'ffff:ffff:ffff:ffff::/64', 'addr': u'2001::1'}]}

Interface names under Windows

Hello,

When calling netifaces.interfaces() under Windows 10 (not tried with other versions), I receive network card ID instead of real names. Even if it's perfectly valid, it's unpracticable to show those names to commmon users in a UX.

Sample :

netifaces.interfaces()
[u'{1853CD13-8E4B-4401-9FBE-D44FB27C300E}', u'{85D7707E-F178-4CCA-851B-46BD51684BBD}', u'{218AD918-B836-4E88-885C-365B94CFD14C}', u'{E9094375-5BC9-49C5-B2D9-7881522F2206}', u'{7105618B-9750-46DE-9365-47F81E0DF41B}', u'{CC8702DA-1B82-4667-9F59-BAEC57F5A8B9}', u'{8922159B-67D7-4597-A1C2-DAF4320B20A6}', u'{FFD7E77E-DF65-11E7-9888-806E6F6E6963}']

Add support for DNS | DHCP client | Wifi WPA Supplicant

Hi,

I like this lib! Great job. I am using Linux. Does the config persists after reboot?

Do you plan to update

  • DNS in /etc/resolv.con
  • Hostname /etc/hostname
    -enable/disable DHCP client for network interfaces
    -WIFI WPA credentials read out /etc/wpa_supplicant.conf

Update installation instructions to reflect wheels

Currently the installation instructions read:

First you need to install it, which you can do by typing:

tar xvzf netifaces-0.10.8.tar.gz
cd netifaces-0.10.8
python setup.py install
Note that you will need the relevant developer tools for your platform, as netifaces is written in C and installing this way will compile the extension.

This does not reflect that wheels are now available and may frighten off many potential users. I suggest something like:

pip install --prefer-binary netifaces will install the latest released wheel for your platform, to use the latest release or if a wheel is not available for your platform you will need the relevant developer tools for your platform as netifaces is written in C. For the latest cutting edge version, complete with any unresolved issues, you can download or check out from GitHub and build with ....

As an aside I would suggest removing the version numbers (0.10.8 above) to reduce the frequency of needing to update the docs.

IPv6 gateway not found on FreeBSD 11.2

On FreeBSD 11.2 netifaces.gateways() only returns IPv4 gateway -

>>> import netifaces
>>> netifaces.gateways()
{'default': {2: ('10.0.2.2', 'em0')}, 2: [('10.0.2.2', 'em0', True)]}
>>> 

The routing table -

$ netstat -r
Routing tables

Internet:
Destination        Gateway            Flags     Netif Expire
default            10.0.2.2           UGS         em0
10.0.2.0/24        link#1             U           em0
10.0.2.15          link#1             UHS         lo0
localhost          link#2             UH          lo0

Internet6:
Destination        Gateway            Flags     Netif Expire
::/96              localhost          UGRS        lo0
default            2002::1            UGS         em0 <<<< not returned by netifaces
localhost          link#2             UH          lo0
::ffff:0.0.0.0/96  localhost          UGRS        lo0
2002::/64          link#1             U           em0
2002::100          link#1             UHS         lo0
fe80::/10          localhost          UGRS        lo0
fe80::%em0/64      link#1             U           em0
fe80::a00:27ff:feb link#1             UHS         lo0
fe80::%lo0/64      link#2             U           lo0
fe80::1%lo0        link#2             UHS         lo0
ff02::/16          localhost          UGRS        lo0

I don't think it makes a difference, but the IPv6 gateway is being added temporarily using -

ifconfig em0 inet6 2002::100/64
route -6 add default 2002::1
ndp -s 2002::1   00:01:02:03:04:05 temp

getifaddrs problems on build

I am experiencing some problems building netifaces on my machine, I am guessing that some libs are missing, but I am not sure which (e.g. ifaddrs.h exists).

Here's the log for python setup.py install:

running install
running bdist_egg
running egg_info
creating netifaces.egg-info
writing netifaces.egg-info/PKG-INFO
writing dependency_links to netifaces.egg-info/dependency_links.txt
writing top-level names to netifaces.egg-info/top_level.txt
writing manifest file 'netifaces.egg-info/SOURCES.txt'
reading manifest file 'netifaces.egg-info/SOURCES.txt'
reading manifest template 'MANIFEST.in'
writing manifest file 'netifaces.egg-info/SOURCES.txt'
installing library code to build/bdist.linux-x86_64/egg
running install_lib
running build_ext
checking for getifaddrs...not found. 
checking for getnameinfo...not found. 
checking for socket IOCTLs...not found. 
checking for optional header files...netash/ash.h netatalk/at.h netax25/ax25.h neteconet/ec.h netipx/ipx.h netpacket/packet.h netrose/rose.h linux/atm.h linux/llc.h linux/tipc.h linux/dn.h. 
checking whether struct sockaddr has a length field...no. 
checking which sockaddr_xxx structs are defined...none! 
checking for routing socket support...no. 
checking for sysctl(CTL_NET...) support...no. 
checking for netlink support...no. 
building 'netifaces' extension
gcc -pthread -B /home/alex/anaconda3/compiler_compat -Wl,--sysroot=/ -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC -DNETIFACES_VERSION=0.10.9 -DHAVE_NETASH_ASH_H=1 -DHAVE_NETATALK_AT_H=1 -DHAVE_NETAX25_AX25_H=1 -DHAVE_NETECONET_EC_H=1 -DHAVE_NETIPX_IPX_H=1 -DHAVE_NETPACKET_PACKET_H=1 -DHAVE_NETROSE_ROSE_H=1 -DHAVE_LINUX_ATM_H=1 -DHAVE_LINUX_LLC_H=1 -DHAVE_LINUX_TIPC_H=1 -DHAVE_LINUX_DN_H=1 -I/home/alex/anaconda3/include/python3.7m -c netifaces.c -o build/temp.linux-x86_64-3.7/netifaces.o
netifaces.c:210:6: error: #error You need to add code for your platform.
 #    error You need to add code for your platform.
      ^~~~~
netifaces.c: In function ‘gateways’:
netifaces.c:1466:22: warning: unused variable ‘defaults’ [-Wunused-variable]
   PyObject *result, *defaults;
                      ^~~~~~~~
At top level:
netifaces.c:689:1: warning: ‘add_to_family’ defined but not used [-Wunused-function]
 add_to_family (PyObject *result, int family, PyObject *obj)
 ^~~~~~~~~~~~~
netifaces.c:438:1: warning: ‘string_from_netmask’ defined but not used [-Wunused-function]
 string_from_netmask (struct sockaddr *addr,
 ^~~~~~~~~~~~~~~~~~~
error: command 'gcc' failed with exit status 1

gcc -v

Using built-in specs.
COLLECT_GCC=gcc
COLLECT_LTO_WRAPPER=/usr/lib/gcc/x86_64-pc-linux-gnu/8.3.0/lto-wrapper
Target: x86_64-pc-linux-gnu
Configured with: /build/gcc/src/gcc/configure --prefix=/usr --libdir=/usr/lib --libexecdir=/usr/lib --mandir=/usr/share/man --infodir=/usr/share/info --with-bugurl=https://bugs.archlinux.org/ --enable-languages=c,c++,ada,fortran,go,lto,objc,obj-c++ --enable-shared --enable-threads=posix --enable-libmpx --with-system-zlib --with-isl --enable-__cxa_atexit --disable-libunwind-exceptions --enable-clocale=gnu --disable-libstdcxx-pch --disable-libssp --enable-gnu-unique-object --enable-linker-build-id --enable-lto --enable-plugin --enable-install-libiberty --with-linker-hash-style=gnu --enable-gnu-indirect-function --enable-multilib --disable-werror --enable-checking=release --enable-default-pie --enable-default-ssp --enable-cet=auto
Thread model: posix
gcc version 8.3.0 (GCC)

uname -r

4.19.45-1-MANJARO

Any ideas?
Thank you!

L.E.

using CC=gcc python setup.py install solves the above, but another problem occurs:

gcc 
    -pthread -shared 
    -B /home/alex/anaconda3/compiler_compat 
    -L /home/alex/anaconda3/lib 
    -Wl,-rpath=/home/alex/anaconda3/lib 
    -Wl,--no-as-needed 
    -Wl,--sysroot=/ 
    -m64 build/temp.linux-x86_64-3.7/netifaces.o 
    -o build/lib.linux-x86_64-3.7/netifaces.cpython-37m-x86_64-linux-gnu.so
build/temp.linux-x86_64-3.7/netifaces.o: file not recognized: file format not recognized

SOLVED
Apparently, there's a problem with anaconda3/compiler_compat/ld and my gcc version. Using system's default ld solved the problem.

Build failure but successful installation on Windows 10 with python 2.7 on 0.10.8

I noticed a weird issue with the netifaces installation on Windows. The build fails but somehow the module still get installed. So far it seems to be working after installation but I'm not using all the module's features, so I'm not sure if anything is broken. The problem does not happen with netifaces 0.10.7, only 0.10.8

Environnement:
Repeated on multiple Windows 10 machines. Issue does not happen on Linux.
Latest python 2.7.15 installed
VCForPython27.msi installed

Steps to reproduce:

  1. Create a python virtual environment with python 2.7:
    virtualenv -p C:\python27\python.exe .pyenv
  2. Activate the python virtual environment:
    .pyenv\Scripts\activate
  3. Install netifaces latest version:
    pip install netifaces==0.10.8

Actual Result:
Gives weird build failure error but installs successfully:

Looking in indexes: https://packagemanager.octasic.com/octasic/current/+simple/
Collecting netifaces==0.10.8
  Downloading https://packagemanager.octasic.com/octasic/pypi/+f/bef/c9800751991c0/netifaces-0.10.8.tar.gz
Building wheels for collected packages: netifaces
  Running setup.py bdist_wheel for netifaces ... error
  Complete output from command d:\scripts\test_stuff\.pyenv\scripts\python.exe -u -c "import setuptools, tokenize;__file__='c:\\users\\xamer\\appdata\\local\\temp\\pip-install-dlcwj0\\netifaces\\setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" bdist_wheel -d c:\users\xamer\appdata\local\temp\pip-wheel-ndovly --python-tag cp27:
  running bdist_wheel
  running build
  running build_ext
  building 'netifaces' extension
  creating build
  creating build\temp.win-amd64-2.7
  creating build\temp.win-amd64-2.7\Release
  C:\Users\xamer\AppData\Local\Programs\Common\Microsoft\Visual C++ for Python\9.0\VC\Bin\amd64\cl.exe /c /nologo /Ox /MD /W3 /GS- /DNDEBUG -DWIN32=1 -DNETIFACES_VERSION=0.10.8 -IC:\python27\include -Id:\scripts\test_stuff\.pyenv\PC /Tcnetifaces.c /Fobuild\temp.win-amd64-2.7\Release\netifaces.obj
  netifaces.c
  creating build\lib.win-amd64-2.7
  C:\Users\xamer\AppData\Local\Programs\Common\Microsoft\Visual C++ for Python\9.0\VC\Bin\amd64\link.exe /DLL /nologo /INCREMENTAL:NO /LIBPATH:C:\python27\Libs /LIBPATH:d:\scripts\test_stuff\.pyenv\libs /LIBPATH:d:\scripts\test_stuff\.pyenv\PCbuild\amd64 /LIBPATH:d:\scripts\test_stuff\.pyenv\PC\VS9.0\amd64 ws2_32.lib iphlpapi.lib /EXPORT:initnetifaces build\temp.win-amd64-2.7\Release\netifaces.obj /OUT:build\lib.win-amd64-2.7\netifaces.pyd /IMPLIB:build\temp.win-amd64-2.7\Release\netifaces.lib /MANIFESTFILE:build\temp.win-amd64-2.7\Release\netifaces.pyd.manifest
     Creating library build\temp.win-amd64-2.7\Release\netifaces.lib and object build\temp.win-amd64-2.7\Release\netifaces.exp
  installing to build\bdist.win-amd64\wheel
  running install
  running install_lib
  creating build\bdist.win-amd64
  creating build\bdist.win-amd64\wheel
  copying build\lib.win-amd64-2.7\netifaces.pyd -> build\bdist.win-amd64\wheel\.
  running install_egg_info
  running egg_info
  writing netifaces.egg-info\PKG-INFO
  writing top-level names to netifaces.egg-info\top_level.txt
  writing dependency_links to netifaces.egg-info\dependency_links.txt
  reading manifest file 'netifaces.egg-info\SOURCES.txt'
  writing manifest file 'netifaces.egg-info\SOURCES.txt'
  Copying netifaces.egg-info to build\bdist.win-amd64\wheel\.\netifaces-0.10.8-py2.7.egg-info
  running install_scripts
  d:\scripts\test_stuff\.pyenv\lib\site-packages\wheel\pep425tags.py:80: RuntimeWarning: Config variable 'Py_DEBUG' is unset, Python ABI tag may be incorrect
    warn=(impl == 'cp')):
  d:\scripts\test_stuff\.pyenv\lib\site-packages\wheel\pep425tags.py:84: RuntimeWarning: Config variable 'WITH_PYMALLOC' is unset, Python ABI tag may be incorrect
    warn=(impl == 'cp')):
  d:\scripts\test_stuff\.pyenv\lib\site-packages\wheel\pep425tags.py:90: RuntimeWarning: Config variable 'Py_UNICODE_SIZE' is unset, Python ABI tag may be incorrect
    sys.version_info < (3, 3))) \
  error: [Errno 2] No such file or directory: 'LICENSE'

  ----------------------------------------
  Failed building wheel for netifaces
  Running setup.py clean for netifaces
Failed to build netifaces
Installing collected packages: netifaces
  Running setup.py install for netifaces ... done
Successfully installed netifaces-0.10.8

Expected Result:
If the build fails it should not install afterwards. Possibly output a clear error message on what to do if build fails.

Let me know if you need more info for troubleshooting.

Repeated build failure on Antegros Linux

I have tried many things to get netifaces to compile and install on my arch linux distribution, Antegros Linux.

Distro: Antergos Linux release 19.1 (ISO-Rolling)
Kernel version: 5.0.1-arch1-1-ARCH

I'm not quite sure what is going on. Looking at the log, something is not quite a right as it seems to be repeatedly unable to find the required headers (specifically, the first thing to fail is the check for ifaddrs.h and related). Those files definetly do exist in their expected places (/usr/include/<#include here>), I confirmed myself. Below are the command outputs:

 $ pip install netifaces
Collecting netifaces
  Using cached https://files.pythonhosted.org/packages/0d/18/fd6e9c71a35b67a73160ec80a49da63d1eed2d2055054cc2995714949132/netifaces-0.10.9.tar.gz
Building wheels for collected packages: netifaces
  Running setup.py bdist_wheel for netifaces ... error
  Complete output from command /home/user/anaconda3/bin/python -u -c "import setuptools, tokenize;__file__='/tmp/pip-install-0w33d5ip/netifaces/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" bdist_wheel -d /tmp/pip-wheel-_5bx9k_n --python-tag cp37:
  running bdist_wheel
  running build
  running build_ext
  checking for getifaddrs...not found.
  checking for getnameinfo...not found.
  checking for socket IOCTLs...not found.
  checking for optional header files...netash/ash.h netatalk/at.h netax25/ax25.h neteconet/ec.h netipx/ipx.h netpacket/packet.h netrose/rose.h linux/atm.h linux/llc.h linux/tipc.h linux/dn.h.
  checking whether struct sockaddr has a length field...no.
  checking which sockaddr_xxx structs are defined...none!
  checking for routing socket support...no.
  checking for sysctl(CTL_NET...) support...no.
  checking for netlink support...no.
  building 'netifaces' extension
  gcc -pthread -B /home/user/anaconda3/compiler_compat -Wl,--sysroot=/ -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC -DNETIFACES_VERSION=0.10.9 -DHAVE_NETASH_ASH_H=1 -DHAVE_NETATALK_AT_H=1 -DHAVE_NETAX25_AX25_H=1 -DHAVE_NETECONET_EC_H=1 -DHAVE_NETIPX_IPX_H=1 -DHAVE_NETPACKET_PACKET_H=1 -DHAVE_NETROSE_ROSE_H=1 -DHAVE_LINUX_ATM_H=1 -DHAVE_LINUX_LLC_H=1 -DHAVE_LINUX_TIPC_H=1 -DHAVE_LINUX_DN_H=1 -I/home/user/anaconda3/include/python3.7m -c netifaces.c -o build/temp.linux-x86_64-3.7/netifaces.o
  netifaces.c:210:6: error: #error You need to add code for your platform.
   #    error You need to add code for your platform.
        ^~~~~
  netifaces.c: In function ‘gateways’:
  netifaces.c:1466:22: warning: unused variable ‘defaults’ [-Wunused-variable]
     PyObject *result, *defaults;
                        ^~~~~~~~
  At top level:
  netifaces.c:689:1: warning: ‘add_to_family’ defined but not used [-Wunused-function]
   add_to_family (PyObject *result, int family, PyObject *obj)
   ^~~~~~~~~~~~~
  netifaces.c:438:1: warning: ‘string_from_netmask’ defined but not used [-Wunused-function]
   string_from_netmask (struct sockaddr *addr,
   ^~~~~~~~~~~~~~~~~~~
  error: command 'gcc' failed with exit status 1
  
  ----------------------------------------
  Failed building wheel for netifaces
  Running setup.py clean for netifaces
Failed to build netifaces
Installing collected packages: netifaces
  Running setup.py install for netifaces ... error
    Complete output from command /home/user/anaconda3/bin/python -u -c "import setuptools, tokenize;__file__='/tmp/pip-install-0w33d5ip/netifaces/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /tmp/pip-record-xxhon2s_/install-record.txt --single-version-externally-managed --compile:
    running install
    running build
    running build_ext
    checking for getifaddrs...not found.
    checking for getnameinfo...not found.
    checking for socket IOCTLs...not found.
    checking for optional header files...netash/ash.h netatalk/at.h netax25/ax25.h neteconet/ec.h netipx/ipx.h netpacket/packet.h netrose/rose.h linux/atm.h linux/llc.h linux/tipc.h linux/dn.h.
    checking whether struct sockaddr has a length field...no.
    checking which sockaddr_xxx structs are defined...none!
    checking for routing socket support...no.
    checking for sysctl(CTL_NET...) support...no.
    checking for netlink support...no.
    building 'netifaces' extension
    gcc -pthread -B /home/user/anaconda3/compiler_compat -Wl,--sysroot=/ -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC -DNETIFACES_VERSION=0.10.9 -DHAVE_NETASH_ASH_H=1 -DHAVE_NETATALK_AT_H=1 -DHAVE_NETAX25_AX25_H=1 -DHAVE_NETECONET_EC_H=1 -DHAVE_NETIPX_IPX_H=1 -DHAVE_NETPACKET_PACKET_H=1 -DHAVE_NETROSE_ROSE_H=1 -DHAVE_LINUX_ATM_H=1 -DHAVE_LINUX_LLC_H=1 -DHAVE_LINUX_TIPC_H=1 -DHAVE_LINUX_DN_H=1 -I/home/user/anaconda3/include/python3.7m -c netifaces.c -o build/temp.linux-x86_64-3.7/netifaces.o
    netifaces.c:210:6: error: #error You need to add code for your platform.
     #    error You need to add code for your platform.
          ^~~~~
    netifaces.c: In function ‘gateways’:
    netifaces.c:1466:22: warning: unused variable ‘defaults’ [-Wunused-variable]
       PyObject *result, *defaults;
                          ^~~~~~~~
    At top level:
    netifaces.c:689:1: warning: ‘add_to_family’ defined but not used [-Wunused-function]
     add_to_family (PyObject *result, int family, PyObject *obj)
     ^~~~~~~~~~~~~
    netifaces.c:438:1: warning: ‘string_from_netmask’ defined but not used [-Wunused-function]
     string_from_netmask (struct sockaddr *addr,
     ^~~~~~~~~~~~~~~~~~~
    error: command 'gcc' failed with exit status 1
    
    ----------------------------------------
Command "/home/user/anaconda3/bin/python -u -c "import setuptools, tokenize;__file__='/tmp/pip-install-0w33d5ip/netifaces/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /tmp/pip-record-xxhon2s_/install-record.txt --single-version-externally-managed --compile" failed with error code 1 in /tmp/pip-install-0w33d5ip/netifaces/

Adding /usr/include to the built_ext options appear to fix the wheel build error, but not the latter:

 $ pip install --global-option=build_ext --global-option="-I/usr/include" netifaces

Manually overriding the incorrect automated header file check, I get a different error:

 $ pip install --global-option=build_ext --global-option="-I/usr/include" --global-option="-DHAVE_GETIFADDRS" netifaces
/home/user/anaconda3/lib/python3.7/site-packages/pip/_internal/commands/install.py:211: UserWarning: Disabling all use of wheels due to the use of --build-options / --global-options / --install-options.
  cmdoptions.check_install_build_global(options)
Collecting netifaces
  Using cached https://files.pythonhosted.org/packages/0d/18/fd6e9c71a35b67a73160ec80a49da63d1eed2d2055054cc2995714949132/netifaces-0.10.9.tar.gz
Skipping bdist_wheel for netifaces, due to binaries being disabled for it.
Installing collected packages: netifaces
  Running setup.py install for netifaces ... error
    Complete output from command /home/user/anaconda3/bin/python -u -c "import setuptools, tokenize;__file__='/tmp/pip-install-00y175g2/netifaces/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" build_ext -I/usr/include -DHAVE_GETIFADDRS install --record /tmp/pip-record-sjxi6fw1/install-record.txt --single-version-externally-managed --compile:
    running build_ext
    checking for getifaddrs...not found.
    checking for getnameinfo...not found.
    checking for socket IOCTLs...not found.
    checking for optional header files...netash/ash.h netatalk/at.h netax25/ax25.h neteconet/ec.h netipx/ipx.h netpacket/packet.h netrose/rose.h linux/atm.h linux/llc.h linux/tipc.h linux/dn.h.
    checking whether struct sockaddr has a length field...no.
    checking which sockaddr_xxx structs are defined...none!
    checking for routing socket support...no.
    checking for sysctl(CTL_NET...) support...no.
    checking for netlink support...no.
    building 'netifaces' extension
    gcc -pthread -B /home/user/anaconda3/compiler_compat -Wl,--sysroot=/ -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC -DNETIFACES_VERSION=0.10.9 -DHAVE_GETIFADDRS=1 -DHAVE_NETASH_ASH_H=1 -DHAVE_NETATALK_AT_H=1 -DHAVE_NETAX25_AX25_H=1 -DHAVE_NETECONET_EC_H=1 -DHAVE_NETIPX_IPX_H=1 -DHAVE_NETPACKET_PACKET_H=1 -DHAVE_NETROSE_ROSE_H=1 -DHAVE_LINUX_ATM_H=1 -DHAVE_LINUX_LLC_H=1 -DHAVE_LINUX_TIPC_H=1 -DHAVE_LINUX_DN_H=1 -I/usr/include -I/home/user/anaconda3/include/python3.7m -c netifaces.c -o build/temp.linux-x86_64-3.7/netifaces.o
    netifaces.c: In function ‘gateways’:
    netifaces.c:1466:22: warning: unused variable ‘defaults’ [-Wunused-variable]
       PyObject *result, *defaults;
                          ^~~~~~~~
    netifaces.c:2532:10: warning: ‘result’ is used uninitialized in this function [-Wuninitialized]
       return result;
              ^~~~~~
    creating build/lib.linux-x86_64-3.7
    gcc -pthread -shared -B /home/user/anaconda3/compiler_compat -L/home/user/anaconda3/lib -Wl,-rpath=/home/user/anaconda3/lib -Wl,--no-as-needed -Wl,--sysroot=/ build/temp.linux-x86_64-3.7/netifaces.o -o build/lib.linux-x86_64-3.7/netifaces.cpython-37m-x86_64-linux-gnu.so
    /home/user/anaconda3/compiler_compat/ld: build/temp.linux-x86_64-3.7/netifaces.o: unable to initialize decompress status for section .debug_info
    /home/user/anaconda3/compiler_compat/ld: build/temp.linux-x86_64-3.7/netifaces.o: unable to initialize decompress status for section .debug_info
    /home/user/anaconda3/compiler_compat/ld: build/temp.linux-x86_64-3.7/netifaces.o: unable to initialize decompress status for section .debug_info
    /home/user/anaconda3/compiler_compat/ld: build/temp.linux-x86_64-3.7/netifaces.o: unable to initialize decompress status for section .debug_info
    build/temp.linux-x86_64-3.7/netifaces.o: file not recognized: file format not recognized
    collect2: error: ld returned 1 exit status
    error: command 'gcc' failed with exit status 1
    
    ----------------------------------------
Command "/home/user/anaconda3/bin/python -u -c "import setuptools, tokenize;__file__='/tmp/pip-install-00y175g2/netifaces/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" build_ext -I/usr/include -DHAVE_GETIFADDRS install --record /tmp/pip-record-sjxi6fw1/install-record.txt --single-version-externally-managed --compile" failed with error code 1 in /tmp/pip-install-00y175g2/netifaces/

netmask and broadcast not returned for 169.254/16 address space on non-Windows

The code for "UNIX" (Linux, MacOS, etc.) iterates over addrs returned by getifaddrs (&addrs). This look has special custom code for that skips over returning netmask and subnet broadcast for 169.254/16. This is the RFC 3927 link-local address space. For better or worse this address space is widely used for simple local networks with no DHCP server. Not returning the broadcast and netmask for this address space confuses people.

Reproduce problem on MacOS as follows:

  1. Set ip address, netmask, and broadcast for en1 to an address in 169.254/16 space:
sudo ifconfig en1 inet 169.254.3.2 netmask 255.255.0.0 broadcast 169.254.255.255
  1. get ifaddresses for en1:
>>> import netifaces
>>> netifaces.interfaces()
[u'lo0', u'gif0', u'stf0', u'XHC20', u'en0', u'p2p0', u'awdl0', u'en1', u'bridge0', u'utun0', u'utun1', u'utun2', u'utun3', u'EHC64', u'fw0']
>>> netifaces.ifaddresses('en1')
{18: [{'addr': u'32:00:12:ec:a0:00'}], 2: [{'addr': u'169.254.3.2'}]}

The "broadcast" and "netmask" keys are missing for 2: (AF_INET).

Correct behavior for en0 in another address space:

>>> netifaces.ifaddresses('en0')
{18: [{'addr': u'48:d7:05:e2:72:09'}], 2: [{'broadcast': u'192.168.1.255', 'netmask': u'255.255.255.0', 'addr': u'192.168.1.7'}], 30: [{'netmask': u'ffff:ffff:ffff:ffff::/64', 'flags': 1024L, 'addr': u'fe80::93:c446:cd4d:e56d%en0'}]}
>>>

The following code applies a policy to 169.254/16 with out regard to OS or correctness of subnet broadcast address. In particular when the broadcast is correctly set to 169.254.255.255, the code suppresses the broadcast address.

    /* Cygwin's implementation of getaddrinfo() is buggy and returns broadcast
       addresses for 169.254.0.0/16.  Nix them here. */
    if (addr->ifa_addr->sa_family == AF_INET) {
      struct sockaddr_in *sin = (struct sockaddr_in *)addr->ifa_addr;

      if ((ntohl(sin->sin_addr.s_addr) & 0xffff0000) == 0xa9fe0000) {
        Py_XDECREF (braddr);
        braddr = NULL;
      }
    }

The Cygwin comment is misleading. There is no specific check for Cygwin. There is no check to make sure a correct 169.254.255.255 is not suppressed. The above code should be removed.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.