[pve-devel] [RFC pve-common] Add generic parse_host_and_port function

Wolfgang Bumiller w.bumiller at proxmox.com
Mon Aug 24 15:14:57 CEST 2015


Added a generic function to split a host+port string to the
host and port part supporting the two most common ipv6
notations beside domains and ipv4: with brackets for the
address or a dot as port separator.
---
 This will be used a few times at least in pve-storage for iSCSI and
 will probably be useful in other areas of the code, too.
 src/PVE/Tools.pm | 23 +++++++++++++++++++++++
 1 file changed, 23 insertions(+)

diff --git a/src/PVE/Tools.pm b/src/PVE/Tools.pm
index a7bcd35..fc5710c 100644
--- a/src/PVE/Tools.pm
+++ b/src/PVE/Tools.pm
@@ -63,6 +63,14 @@ our $IPV6RE = "(?:" .
     "(?:(?:(?:(?:$IPV6H16:){0,5}$IPV6H16)?::" .            ")$IPV6H16)|" .
     "(?:(?:(?:(?:$IPV6H16:){0,6}$IPV6H16)?::" .                    ")))";
 
+our $DOMAIN_RE = qr/[[:alnum:]\-.]+/;
+our $IP_OR_DOMAIN_RE = qr/$IPV4RE|$IPV6RE|$DOMAIN_RE/;
+our $IP_OR_DOMAIN_WITH_PORT_RE = qr/(?<ADDRESS>$IPV6RE)(?:\.(?<PORT>\d+))?
+                                   |(?:\[(?<ADDRESS>$IP_OR_DOMAIN_RE)\]
+                                      |(?<ADDRESS>$IPV4RE|$DOMAIN_RE))
+                                    (?::(?<PORT>\d+))?
+                                   /x;
+
 sub run_with_timeout {
     my ($timeout, $code, @param) = @_;
 
@@ -1102,4 +1110,19 @@ sub get_host_address_family {
     return $res[0]->{family};
 }
 
+# Parses any sane kind of host, or host+port pair:
+#   The usual: name-or-ipv4:port
+#   The mostly available: [name-or-address]:port
+#   The alternative variant: ipv6.port
+# The port is always optional and thus may be undef.
+sub parse_host_and_port {
+    my ($address) = @_;
+    if ($address =~ /^$IP_OR_DOMAIN_WITH_PORT_RE$/) {
+	# appending a 1 so scalar-context evaluates to true even without a port
+	# so we can simply use "if(parse...)" to test the correctness of an address
+	return ($+{ADDRESS}, $+{PORT}, 1);
+    }
+    return undef;
+}
+
 1;
-- 
2.1.4





More information about the pve-devel mailing list