From cb0dee93926f7658560f84496225b1efd80b5035 Mon Sep 17 00:00:00 2001 From: "A. Wilcox" Date: Fri, 11 Dec 2020 07:09:42 -0600 Subject: ifupdown-ng NMSA: Add live_addresses method --- ncserver/module/nms_ifupdownng.py | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/ncserver/module/nms_ifupdownng.py b/ncserver/module/nms_ifupdownng.py index 1142f31..7c1746e 100644 --- a/ncserver/module/nms_ifupdownng.py +++ b/ncserver/module/nms_ifupdownng.py @@ -12,7 +12,9 @@ SPDX-License-Identifier: NCSA from contextlib import contextmanager +import ipaddress import logging +import netifaces import pathlib import socket import subprocess @@ -684,6 +686,30 @@ def list_addresses(iface: str) -> list: return _find_many(iface, 'address') +def live_addresses(iface: str) -> list: + """Retrieve live addresses for the specified interface.""" + addresses = list() + + if iface not in netifaces.interfaces(): + LOGGER.warning(_("interface %s is not live"), iface) + return addresses + + raw = netifaces.ifaddresses(iface) + for v4 in raw.get(socket.AF_INET, tuple()): + addr = v4['addr'] + mask = v4['netmask'] + iface = ipaddress.IPv4Interface("{a}/{m}".format(a=addr, m=mask)) + addresses.append(iface) + + for v6 in raw.get(socket.AF_INET6, tuple()): + addr = v6['addr'].split('%')[0] + mask = v6['netmask'][v6['netmask'].find('/') + 1:] + iface = ipaddress.IPv6Interface("{a}/{m}".format(a=addr, m=mask)) + addresses.append(iface) + + return addresses + + def add_address(iface: str, _type, addr: str, prefix): """Add an address of the specified ``type`` to the specified interface.""" _load_config() -- cgit v1.2.3-60-g2f50