NYCPHP Meetup

NYPHP.org

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

Phil Powell soazine at erols.com
Fri Aug 15 01:29:47 EDT 2003


 have written a function that is supposed to compare the first three nodes of an IP address, but it is riddled with errors that I have given up trying to figure out.

Is there an existing function out there that can do this? I want to compare "127.0.0.1" with "127.0.0.100" and come with as a "match", or "127.0.0.1" with "127.0.0.1", but no "match if "127.0.0.1" and "127.255.0.0".

Here is what I have:

/*--------------------------------------------------------------------------------------------
    This function will compare the first three instances of an IP address by splitting apart,
    gathering into a string the first three IP address nodes, and then returning strcmp of the
    two.  Will return a 1 if they are identical, otherwise, will return a 0.
  ---------------------------------------------------------------------------------------------*/
  function ip_isThreeNodeIdentical($ip1, $ip2) {
   if (!preg_match('/^([0-9]+\.)+[0-9]+$/i', $ip1) || !preg_match('/^([0-9]+\.)+[0-9]+$/i', $ip2)) {
    return 0;
   } else {
    $ip_array1 = explode('.', $ip1); $ip_array2 = explode('.', $ip2);
    foreach (array('1', '2') as $key => $val) {
     $ipArrayVal = 'ip_array' . $val; $ipCompareVal = 'ipCompare' . $val;
     for ($i = 0; $i < sizeof(${$ipArrayVal}) - 1; $i++) 
      ${ipCompareVal} .= ${ipArrayVal}[$i] . '.';
     ${ipCompareVal} = substr(${ipCompareVal}, 0, strrpos(${ipCompareVal), '.') - 1); 
    }
    return (strcmp($ipCompare1, $ipCompare2) == 0) ? 1 : 0;
   }
  }

I tried. :(

Phil
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.nyphp.org/pipermail/talk/attachments/20030815/a670fae1/attachment.html>


More information about the talk mailing list