NYCPHP Meetup

[nycphp-talk] I need a function that will compare IP addresses

Wellington Fan wfan at encogent.com
Mon Aug 18 15:18:47 EDT 2003


Folks!

Try this:

<?php
function compareIPs($ip1,$ip2,$subnet='255.255.255.0') {
	$ip1quads = explode('.',$ip1);
	$ip2quads = explode('.',$ip2);
	$snquads = explode('.',$subnet);

	$identical = true;
	foreach( $snquads as $i => $mask) {
		$masked1 = (int) $ip1quads[$i] & (int) $mask;
		$masked2 = (int) $ip2quads[$i] & (int) $mask;
		$identical &= ($masked1 == $masked2 ? true:false);
	}

	return $identical;
}


echo '<li>'.compareIPs('192.168.0.3','192.168.0.4');
echo '<li>'.compareIPs('192.168.1.3','192.168.0.4');
echo '<li>'.compareIPs('192.168.1.3','192.168.0.4','255.255.0.0');
echo '<li>'.compareIPs('10.0.0.1','10.0.0.2','255.0.0.0');

?>


compareIPs will take 2 or 3 parameters; each is a dotted quad passed in as a
string.

The last parameter is the subnet mask (or netmask), and the default value is
'255.255.255.0' which ignores the last quad when comparing.

--
Wellington





More information about the talk mailing list