[pve-devel] [PATCH common 2/2] tools: add addr_to_ip helper

Wolfgang Bumiller w.bumiller at proxmox.com
Mon Apr 24 15:52:01 CEST 2017


Converts a packed address into a numerical string.
(Optionally includes the port).
---
 src/PVE/Tools.pm | 11 ++++++++++-
 1 file changed, 10 insertions(+), 1 deletion(-)

diff --git a/src/PVE/Tools.pm b/src/PVE/Tools.pm
index 36a9f5a..dd63e65 100644
--- a/src/PVE/Tools.pm
+++ b/src/PVE/Tools.pm
@@ -4,7 +4,8 @@ use strict;
 use warnings;
 use POSIX qw(EINTR EEXIST EOPNOTSUPP);
 use IO::Socket::IP;
-use Socket qw(AF_INET AF_INET6 AI_ALL AI_V4MAPPED AI_CANONNAME SOCK_DGRAM);
+use Socket qw(AF_INET AF_INET6 AI_ALL AI_V4MAPPED AI_CANONNAME SOCK_DGRAM
+	      NI_NUMERICHOST NI_NUMERICSERV);
 use IO::Select;
 use File::Basename;
 use File::Path qw(make_path);
@@ -1200,6 +1201,14 @@ sub get_host_address_family {
     return $res[0]->{family};
 }
 
+sub addr_to_ip {
+    my ($addr) = @_;
+    my ($err, $host, $port) = Socket::getnameinfo($addr, NI_NUMERICHOST | NI_NUMERICSERV);
+    die "failed to get numerical host address: $err\n" if $err;
+    return ($host, $port) if wantarray;
+    return $host;
+}
+
 # get the fully qualified domain name of a host
 # same logic as hostname(1): The FQDN is the name getaddrinfo(3) returns,
 # given a nodename as a parameter
-- 
2.11.0





More information about the pve-devel mailing list