Gathering information with the netifaces package

Now, we are going to discover some more information about the network interface and the gateway machine of your network.

In every LAN, a host is configured to act as a gateway, which talks to the outside world. To find the network address and the netmask, we can use a Python third-party library, netifaces. For example, you can call netifaces.gateways() to find the gateways that are configured to the outside world. Similarly, you can enumerate the network interfaces by calling netifaces.interfaces(). If you would like to know all the IP addresses of a particular interface, eth0, then you can call netifaces.ifaddresses('eth0').

The following code listing shows the way in which you can list all the gateways and IP addresses of a local machine.

You can find the following code in the local_network_config.py file:

!/usr/bin/env python3

import socket
import netifaces

# Find host info
host_name = socket.gethostname()
ip_address = socket.gethostbyname(host_name)
print("Host name: {0}".format(host_name))

# Get interfaces list
ifaces = netifaces.interfaces()

for iface in ifaces:
ipaddrs = netifaces.ifaddresses(iface)
#for each ipaddress
if netifaces.AF_INET in ipaddrs:
ipaddr_desc = ipaddrs[netifaces.AF_INET]
ipaddr_desc = ipaddr_desc[0]
print("Network interface: {0}".format(iface))
if 'addr' in ipaddr_desc:
print(" IP address: {0}".format(ipaddr_desc['addr']))
if 'netmask' in ipaddr_desc:
print(" Netmask: {0}".format(ipaddr_desc['netmask']))

# Find the gateway
gateways = netifaces.gateways()
print("Default gateway:{0}".format(gateways['default'][netifaces.AF_INET][0]))

If you run this code in a Windows operating system, it will print a summary of the local network configuration, which will be similar to the following:

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset