What is Python network interface?
Definition
According to Wikipedia:
In computing, a network interface is a software or hardware interface between two pieces of equipment or protocol layers in a computer network. A network interface will usually have some form of network address. This may consist of a node identifier and a port number or it may be a unique node ID in its own right. Network interfaces provide standardized functions such as passing messages, connecting, disconnecting, etc.
Python netifaces module
There is no easy way to get addresses of network interfaces using Python, so to solve this, we have the netifaces library.
We will go through how to install and use netifaces step by step.
Install and import
- Install this module with
pip:
pip install netifaces
- After installation, import this module:
import netifacesprint("successfully imported netifaces")
How to use netifaces
- List the network interface identifiers:
import netifacesprint(netifaces.interfaces())
-
Get the addresses of a particular interface:
- After executing the code above, it will print a list of network interface identifiers.
- Take one of those and pass it to
netifaces.ifaddresses('lo')to get addresses for that specific network interface.
-
The code snippet below outputs a dictionary, where keys are numbers that refer to a particular address family.
Note: Numbers may be different from system to system.
import netifacesprint(netifaces.ifaddresses('lo'))
- Get
AF_INETandAF_LINKaddresses for the particular network interface.
import netifacesaddrs = netifaces.ifaddresses('lo')print("AF_INET: "+str(addrs[netifaces.AF_INET]))print("AF_LINK: "+str(addrs[netifaces.AF_LINK]))