Python netifaces

From wikinotes
Revision as of 22:32, 13 October 2016 by Will (talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

netifaces provides a means of programmatically getting information about your network devices, connections, interfaces etc. The library can be a bit inconvenient to work with, but it solves a enormous issue for me that previously could only be solved with elaborate parsing of ifconfig/ip's output. Thank god that is done with.





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