Detect network interfaces with IP addresses.
()
| 67 | |
| 68 | |
| 69 | def detect_interfaces(): |
| 70 | """Detect network interfaces with IP addresses.""" |
| 71 | interfaces = [] |
| 72 | |
| 73 | try: |
| 74 | if sys.platform == 'win32': |
| 75 | # Windows: use ipconfig parsing |
| 76 | result = subprocess.run(['ipconfig'], capture_output=True, text=True, timeout=5) |
| 77 | current_iface = None |
| 78 | for line in result.stdout.split('\n'): |
| 79 | line = line.rstrip() |
| 80 | if line and not line[0].isspace() and ':' in line: |
| 81 | current_iface = line.split(':')[0].strip() |
| 82 | # Clean up adapter name |
| 83 | for prefix in ['Ethernet adapter ', 'Wireless LAN adapter ', |
| 84 | 'Ethernet-kort ', 'Tr\xe5dl\xf6st n\xe4tverkskort ']: |
| 85 | if current_iface.startswith(prefix): |
| 86 | current_iface = current_iface[len(prefix):] |
| 87 | elif current_iface and ('IPv4' in line or 'IPv4' in line.replace('v', 'v')): |
| 88 | parts = line.split(':') |
| 89 | if len(parts) >= 2: |
| 90 | ip = parts[-1].strip() |
| 91 | if ip and ip != '127.0.0.1' and not ip.startswith('169.254'): |
| 92 | interfaces.append({ |
| 93 | 'name': current_iface, |
| 94 | 'ip': ip, |
| 95 | 'subnet': ip + '/24', |
| 96 | }) |
| 97 | current_iface = None |
| 98 | else: |
| 99 | # Linux: use ip addr |
| 100 | result = subprocess.run(['ip', 'addr'], capture_output=True, text=True, timeout=5) |
| 101 | current_iface = None |
| 102 | for line in result.stdout.split('\n'): |
| 103 | if line and not line[0].isspace() and ':' in line: |
| 104 | parts = line.split(':') |
| 105 | if len(parts) >= 2: |
| 106 | current_iface = parts[1].strip() |
| 107 | elif 'inet ' in line and current_iface: |
| 108 | parts = line.strip().split() |
| 109 | for i, p in enumerate(parts): |
| 110 | if p == 'inet' and i + 1 < len(parts): |
| 111 | cidr = parts[i + 1] |
| 112 | ip = cidr.split('/')[0] |
| 113 | if ip != '127.0.0.1': |
| 114 | interfaces.append({ |
| 115 | 'name': current_iface, |
| 116 | 'ip': ip, |
| 117 | 'subnet': cidr, |
| 118 | }) |
| 119 | break |
| 120 | except Exception: |
| 121 | pass |
| 122 | return interfaces |
| 123 | |
| 124 | |
| 125 | class RagnarMenu: |