]> git.ipfire.org Git - people/ms/ipfire-2.x.git/commitdiff
network-functions.pl: Add function to extract prefix
authorMichael Tremer <michael.tremer@ipfire.org>
Wed, 20 Mar 2024 11:09:58 +0000 (12:09 +0100)
committerMichael Tremer <michael.tremer@ipfire.org>
Sat, 27 Apr 2024 17:30:09 +0000 (19:30 +0200)
Signed-off-by: Michael Tremer <michael.tremer@ipfire.org>
config/cfgroot/network-functions.pl

index 7b38cfac7f9645d5ab1a29c6d4793429ee62500a..bf827a036222af63dad3c6561a45e20d91c693b7 100644 (file)
@@ -291,6 +291,33 @@ sub get_broadcast($) {
        return &bin2ip($network_bin ^ ~$netmask_bin);
 }
 
+sub get_prefix($) {
+       my $network = shift;
+
+       # Convert to binary
+       my ($network_bin, $netmask_bin) = &network2bin($network);
+
+       if (defined $netmask_bin) {
+               my $prefix = 0;
+
+               while (1) {
+                       # End the loop if we have consumed all ones
+                       last if ($netmask_bin == 0);
+
+                       # Increment prefix
+                       $prefix++;
+
+                       # Remove the most-significant one
+                       $netmask_bin <<= 1;
+                       $netmask_bin &= 0xffffffff;
+               }
+
+               return $prefix;
+       }
+
+       return undef;
+}
+
 # Returns True if $address is in $network.
 sub ip_address_in_network($$) {
        my $address = shift;
@@ -690,6 +717,13 @@ 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 &get_prefix()
+       $result = &get_prefix("192.168.0.0/24");
+       assert('get_prefix("192.168.0.0/24")', $result != 24);
+
+       $result = &get_prefix("192.168.0.0/255.255.0.0");
+       assert('get_prefix("192.168.0.0/255.255.0.0")', $result != 16);
+
        print "Testsuite completed successfully!\n";
 
        return 0;