[1/4] network-functions.pl: Add ip_address_is_global()

Message ID 20261201143155.1798388-2-antonio@mandelbit.com
State Staged
Commit 052996cff73095a3b6cf18cb239ef88ff91a5864
Headers
Series Use the address ddns publishes in the DDNS sync check (#14766) |

Commit Message

Antonio Quartulli 1 Dec 2026, 2:31 p.m. UTC
Returns whether an IPv4 address can be reached from the Internet, based
on the IANA special-purpose address registry.

Signed-off-by: Antonio Quartulli <antonio@mandelbit.com>
---
 config/cfgroot/network-functions.pl | 29 +++++++++++++++++++++++++++++
 1 file changed, 29 insertions(+)
  

Patch

diff --git a/config/cfgroot/network-functions.pl b/config/cfgroot/network-functions.pl
index a90655305..9f37c490f 100644
--- a/config/cfgroot/network-functions.pl
+++ b/config/cfgroot/network-functions.pl
@@ -425,6 +425,23 @@  sub ip_address_in_range($$) {
 	return (($ipaddress_bin >= $ipstart_bin) && ($ipaddress_bin <= $ipend_bin));
 }
 
+# Returns true if the IPv4 address can be reached from the Internet, i.e. it
+# isn't in any of the special-purpose ranges that aren't globally reachable
+# (based on the IANA registry).
+sub ip_address_is_global($) {
+	my $address = shift;
+
+	return 0 unless (&check_ip_address($address));
+
+	foreach my $network ("0.0.0.0/8", "10.0.0.0/8", "100.64.0.0/10", "127.0.0.0/8",
+			"169.254.0.0/16", "172.16.0.0/12", "192.0.0.0/24", "192.0.2.0/24", "192.168.0.0/16",
+			"198.18.0.0/15", "198.51.100.0/24", "203.0.113.0/24", "240.0.0.0/4") {
+		return 0 if (&ip_address_in_network($address, $network));
+	}
+
+	return 1;
+}
+
 sub check_port
 {
 	$_ = $_[0];
@@ -1022,6 +1039,18 @@  sub testsuite() {
 	$result = &ip_address_in_range("192.168.30.21", "192.168.30.10", "192.168.30.20");
 	assert('ip_address_in_range("192.168.30.21", "192.168.30.10", "192.168.30.20")', !$result);
 
+	# Check &ip_address_is_global()
+	foreach my $address ("81.3.27.37", "8.8.8.8", "1.0.0.0", "100.63.255.255", "100.128.0.0",
+			"169.253.255.255", "172.15.255.255", "172.32.0.0", "224.0.0.1", "239.255.255.255") {
+		assert("ip_address_is_global(\"$address\")", &ip_address_is_global($address));
+	}
+
+	foreach my $address ("10.1.2.3", "172.16.0.0", "172.31.255.255", "192.168.1.1", "100.64.0.0",
+			"100.127.255.255", "127.0.0.1", "169.254.0.0", "169.254.255.255", "0.255.255.255",
+			"192.0.2.1", "198.18.0.1", "240.0.0.0", "255.255.255.255", "a.b.c.d", "") {
+		assert("!ip_address_is_global(\"$address\")", !&ip_address_is_global($address));
+	}
+
 	# Check &get_prefix()
 	$result = &get_prefix("192.168.0.0/24");
 	assert('get_prefix("192.168.0.0/24")', $result == 24);