Python netifaces

From wikinotes

python library to get information about network interfaces.

Concepts

Some of this library's ackwardness is attributed to the spindly nature of the various implementations of network-interfaces.

  • Network connections are made to your computer through network-interfaces.
  • Network interfaces are capable of binding different types of connections (ipv4,ipv6,bluetooth,...)

Internally, these various types are represented by an ID (this differs on different platforms and chip manufacturers)

  • Multiple addresses can be bound to the same network interface (ip aliasing etc, ipv4 && ipv6 etc)

Usage

ip_addrs       = {}
ifaces         = netifaces.interfaces()                     ## get a list of all interfaces ['eth0','lo','wlp3s0',...]
ipaddr_typeids = (netifaces.AF_INET, netifaces.AF_INET6)    ## ids representing ipv4 or ipv6

for iface in ifaces:
	bindings[ iface ] = []
	bound_addrs = netifaces.ifaddresses( 'eth0' )            ## get a list of all bindings to an address

	for addr_typeid in bound_addrs:
		if addr_typeid in ipaddr_typeids:
			bindings[ iface ].extend( bound_addrs[ addr_typeid ] )

Elements

Interfaces

ifaces = netifaces.interfaces()  ## list of all interfaces ['eth0','lo',...]

netifaces.ifaddresses( 'eth0' )  ## list of all bindings to interface { binding_typeid : [ {...}, {...} ] }

Address TypeIds

netifaces.AF_LINK    ## hardware addresses(MAC), bluetooth, ...
netifaces.AF_INET    ## ipv4
netifaces.AF_INET6   ## ipv6