views:

80

answers:

1

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?

+1  A: 

Technically what "ip addr sh" does is use the netlink library to interrogate (and optionally monitor) the kernel network interfaces / routing tables.

You might be able to do this in python, but I strongly recommend parsing the output of "/sbin/ip addr sh"

This is because

  • Using the rtnetlink library is complicated
  • You don't care about performance - network interfaces don't change often enough that you care (and in any case you can monitor them using "ip monitor")
MarkR
Thanks. I had a quick look at rtnetlink, and you're right in that it seems overly complex for this task. Parsing `ip addr show` still feels a bit hackish, but I guess it's the best way forward in this case.
Pär Wieslander