Return IPv4 metadata (address, prefix, netmask, network) for an interface.
(interface_name: str)
| 35 | |
| 36 | |
| 37 | def _get_interface_ipv4_details(interface_name: str) -> Dict[str, Optional[str]]: |
| 38 | """Return IPv4 metadata (address, prefix, netmask, network) for an interface.""" |
| 39 | try: |
| 40 | result = subprocess.run( |
| 41 | ['ip', '-o', '-4', 'addr', 'show', interface_name], |
| 42 | capture_output=True, |
| 43 | text=True, |
| 44 | timeout=3 |
| 45 | ) |
| 46 | if result.returncode != 0 or not result.stdout: |
| 47 | return { |
| 48 | 'ip': None, |
| 49 | 'cidr': None, |
| 50 | 'netmask': None, |
| 51 | 'network': None, |
| 52 | } |
| 53 | match = re.search(r'inet\s+([0-9.]+)/([0-9]+)', result.stdout) |
| 54 | if not match: |
| 55 | return { |
| 56 | 'ip': None, |
| 57 | 'cidr': None, |
| 58 | 'netmask': None, |
| 59 | 'network': None, |
| 60 | } |
| 61 | ip_value = match.group(1) |
| 62 | prefix = int(match.group(2)) |
| 63 | iface = ipaddress.IPv4Interface(f"{ip_value}/{prefix}") |
| 64 | return { |
| 65 | 'ip': ip_value, |
| 66 | 'cidr': prefix, |
| 67 | 'netmask': str(iface.netmask), |
| 68 | 'network': str(iface.network), |
| 69 | } |
| 70 | except Exception as exc: |
| 71 | logger.debug(f"Unable to read IP address for {interface_name}: {exc}") |
| 72 | return { |
| 73 | 'ip': None, |
| 74 | 'cidr': None, |
| 75 | 'netmask': None, |
| 76 | 'network': None, |
| 77 | } |
| 78 | |
| 79 | |
| 80 | def _infer_frequency_band(freq_mhz: Optional[int]) -> Optional[str]: |
no test coverage detected