Check if the IP address is on the network

I am looking for a function to determine if a given IPv4 address is on a given network.

It will be similar to this ; however, I do not want to establish a complete structure or reinvent the wheel if it is not necessary.

The idea will be similar to the following:

function IsInNetwork($givenIP, $networkIP, $netmask) { // ??? } $valid = IsInNetwork("10.0.9.35", "10.0.8.0", "255.255.254.0"); 

- EDIT -

With Rich Adams, he pointed me in the right direction and came up with the following:

 function IsInNetwork2($givenIP, $networkIP, $netmask) { $ipaddr = ip2long($givenIP); $netip = ip2long($networkIP); $netmask = (ip2long($netmask) * -1) + $netip; if ($ipaddr >= $netip && $ipaddr <= $netmask){ return true; } else { return false; } } 
+4
source share
1 answer

Something like this should work,

 function IsInNetwork($givenIP, $networkIP, $netmask) { return ((ip2long($givenIP) & ip2long($networkIP)) == ip2long($network)); } $valid = IsInNetwork("10.0.9.35", "10.0.8.0", "255.255.254.0"); // true 
+4
source

Source: https://habr.com/ru/post/1387446/


All Articles