machine: improve LAN IP detection

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
This commit is contained in:
Eric Callahan 2022-08-08 19:20:56 -04:00
parent 8bbd269084
commit c4e370fcff
No known key found for this signature in database
GPG Key ID: 5A1EB336DFB4C71B
1 changed files with 18 additions and 10 deletions

View File

@ -438,15 +438,23 @@ class Machine:
# However, it would be better to use NETLINK for this rather # However, it would be better to use NETLINK for this rather
# than run another shell command # than run another shell command
src_ip: Optional[str] = None src_ip: Optional[str] = None
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # First attempt: use "broadcast" to find the local IP
try: addr_info = [("<broadcast>", 0, False), ("10.255.255.255", 1, True)]
s.settimeout(0) for (addr, port, bcast) in addr_info:
s.connect(('10.255.255.255', 1)) s = socket.socket(
src_ip = s.getsockname()[0] socket.AF_INET, socket.SOCK_DGRAM | socket.SOCK_NONBLOCK
except Exception: )
pass try:
finally: if bcast:
s.close() s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
s.connect((addr, port))
src_ip = s.getsockname()[0]
except Exception:
continue
logging.info(f"Detected Local IP: {src_ip}")
return src_ip
if src_ip is None:
logging.info("Failed to detect local IP address")
return src_ip return src_ip
async def _get_wifi_interfaces(self) -> Dict[str, Any]: async def _get_wifi_interfaces(self) -> Dict[str, Any]:
@ -456,7 +464,7 @@ class Machine:
try: try:
resp = await self.iwgetid_cmd.run_with_response(log_complete=False) resp = await self.iwgetid_cmd.run_with_response(log_complete=False)
except shell_cmd.error: except shell_cmd.error:
logging.exception("Failed to run 'iwgetid' command") logging.info("Failed to run 'iwgetid' command")
return {} return {}
if resp: if resp:
for line in resp.split("\n"): for line in resp.split("\n"):