I need to list the available network interfaces and their IP addresses and corresponding netmasks using Python in a Linux environment. I can get the interfaces and the IP addresses of each interface using ioctl
and SIOCGIFCONF
as outlined here, but I'm at loss when it comes to determining the netmask when there are multiple IP address on an interface.
I can get the netmask of the primary IP address of an interface as suggested in Retrieving network mask in Python:
import socket
import fcntl
import struct
SIOCGIFNETMASK = 0x891b
def get_network_mask(ifname):
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
netmask = fcntl.ioctl(s, SIOCGIFNETMASK, struct.pack('256s', ifname))[20:24]
return socket.inet_ntoa(netmask)
>>> get_network_mask('eth0')
'255.255.255.0'
However, this won't work if I have multiple IP addresses with different netmasks on the same interface, as follows:
$ ip addr show eth0
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UNKNOWN qlen 1000
inet 192.168.1.1/16 brd 192.168.255.255 scope global eth0
inet 172.16.0.123/24 scope global eth0
In this case I'll only be able to retrieve one of the netmasks using the above function. Is there a way to retrieve the netmasks for all addresses, except by parsing the output from ip addr show
or ifconfig
?