开发者

Retrieving netmask for interfaces with multiple IP addresses using Python?

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 S开发者_C百科IOCGIFCONF 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?


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")
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜