From b57997fc19aa25610b67f44778e3bd9550b88ed3 Mon Sep 17 00:00:00 2001 From: Sebastian Wiesner Date: Thu, 19 Dec 2024 16:57:10 +0100 Subject: [PATCH] Reverse lookup devices from ARP cache Closes #50 --- resources/de.swsnr.turnon.metainfo.xml.in | 1 + src/app/model/device_discovery.rs | 46 ++++++++++++++++++++--- 2 files changed, 41 insertions(+), 6 deletions(-) diff --git a/resources/de.swsnr.turnon.metainfo.xml.in b/resources/de.swsnr.turnon.metainfo.xml.in index 06c719e..cdcd65f 100644 --- a/resources/de.swsnr.turnon.metainfo.xml.in +++ b/resources/de.swsnr.turnon.metainfo.xml.in @@ -39,6 +39,7 @@ GH-4 + GH-50 https://github.com/swsnr/turnon/releases/tag/next diff --git a/src/app/model/device_discovery.rs b/src/app/model/device_discovery.rs index bf585f6..8564e42 100644 --- a/src/app/model/device_discovery.rs +++ b/src/app/model/device_discovery.rs @@ -8,11 +8,12 @@ use std::path::Path; use glib::{dpgettext2, Object}; use gtk::gio; +use gtk::gio::prelude::*; +use crate::config::G_LOG_DOMAIN; use crate::net::arpcache::*; use super::Device; -use crate::config::G_LOG_DOMAIN; glib::wrapper! { /// Device discovery. @@ -30,13 +31,14 @@ mod imp { use gtk::gio::prelude::*; use gtk::gio::subclass::prelude::*; - use std::{ - cell::{Cell, RefCell}, - path::PathBuf, - }; + use std::cell::{Cell, RefCell}; + use std::path::PathBuf; + use crate::config::G_LOG_DOMAIN; + use crate::net::arpcache::default_arp_cache_path; + + use super::resolve_device_host_to_label; use super::{super::Device, devices_from_arp_cache}; - use crate::{config::G_LOG_DOMAIN, net::arpcache::default_arp_cache_path}; #[derive(Debug, glib::Properties)] #[properties(wrapper_type = super::DeviceDiscovery)] @@ -66,6 +68,7 @@ mod imp { } } + /// Scan the local ARP cache for devices. fn scan_devices(&self) { let discovery = self.obj().clone(); glib::spawn_future_local(async move { @@ -83,6 +86,7 @@ mod imp { 0, n_changed.try_into().unwrap(), ); + discovery.imp().reverse_lookup_devices(); } } Err(error) => { @@ -91,6 +95,19 @@ mod imp { } }); } + + /// Reverse-lookup the DNS names of all currently discovered devices. + fn reverse_lookup_devices(&self) { + for device in self.discovered_devices.borrow().iter() { + glib::spawn_future_local(glib::clone!( + #[weak] + device, + async move { + resolve_device_host_to_label(device).await; + } + )); + } + } } #[glib::object_subclass] @@ -131,6 +148,23 @@ mod imp { } } +/// Resolve the host of `device` to a DNS name and use it as label. +async fn resolve_device_host_to_label(device: Device) { + if let Some(address) = gio::InetAddress::from_string(&device.host()) { + match gio::Resolver::default() + .lookup_by_address_future(&address) + .await + { + Ok(name) => { + device.set_label(name); + } + Err(error) => { + glib::warn!("Failed to resolve address {address} into DNS name: {error}"); + } + } + } +} + /// Read devices from the ARP cache. /// /// Return an error if opening the ARP cache file failed; otherwise return a