[pve-devel] [PATCH installer 2/5] run env: retrieve and store hostname from DHCP lease if available

Christoph Heiss c.heiss at proxmox.com
Fri Oct 20 11:46:45 CEST 2023


Signed-off-by: Christoph Heiss <c.heiss at proxmox.com>
---
 Proxmox/Install/RunEnv.pm |  4 ++++
 Proxmox/Sys/Net.pm        | 25 +++++++++++++++++++++++++
 2 files changed, 29 insertions(+)

diff --git a/Proxmox/Install/RunEnv.pm b/Proxmox/Install/RunEnv.pm
index 19b5387..7589679 100644
--- a/Proxmox/Install/RunEnv.pm
+++ b/Proxmox/Install/RunEnv.pm
@@ -263,6 +263,10 @@ sub query_installation_environment : prototype() {
 	routes => $routes,
 	dns => query_dns(),
     };
+
+    # Cannot be put directly in the above hash as it might return undef ..
+    $output->{network}->{hostname} = Proxmox::Sys::Net::get_dhcp_hostname();
+
     # FIXME: move whatever makes sense over to Proxmox::Sys::Net:: and keep that as single source,
     # it can then use some different structure just fine (after adapting the GTK GUI to that) but
     # **never** to (slightly different!) things for the same stuff...
diff --git a/Proxmox/Sys/Net.pm b/Proxmox/Sys/Net.pm
index f5a9885..35d2abd 100644
--- a/Proxmox/Sys/Net.pm
+++ b/Proxmox/Sys/Net.pm
@@ -189,4 +189,29 @@ sub get_ip_config {
     }
 }
 
+# Tries to detect the hostname for this system via DHCP, if available.
+# DHCP server can set option 12 to inform the client about it's hostname [0].
+# dhclient dumps all options set by the DHCP server it in lease file, so just
+# read it from there.
+# [0] RFC 2132, section 3.14
+sub get_dhcp_hostname : prototype() {
+    my $leasefile = '/var/lib/dhcp/dhclient.leases';
+    return if ! -f $leasefile;
+
+    open (my $fh, '<', $leasefile) or return;
+
+    my $name = undef;
+    while (my $line = <$fh>) {
+	# "The name may or may not be qualified with the local domain name"
+	# Thus, only match the first part.
+	if ($line =~ m/^\s+option host-name \"(${FQDN_RE})\";$/) {
+	    $name = $1;
+	    last;
+	}
+    }
+
+    close($fh);
+    return $1 if defined($name) && $name =~ m/^([^\.]+)(?:\.(?:\S+))?$/;
+}
+
 1;
-- 
2.42.0






More information about the pve-devel mailing list