Results 1 to 3 of 3

Thread: [RESOLVED] Check if valid IP Address

Hybrid View

  1. #1

    Thread Starter
    Fanatic Member
    Join Date
    Sep 2005
    Posts
    540

    Re: Check if valid IP Address

    Don't worry... figured it out!

    Code:
    function checkIPAddress($ipAddressCheck, $networkAddress, $subnetMask)
    {
      $subnetBin=(pow(2,32)-1)-(pow(2,32-$subnetMask)-1);
      $firstIP=ip2long($networkAddress) & ($subnetBin);
      $NetworkLength=pow(2,32-$subnetMask)-1;
      $longIPAddressCheck = ip2long($ipAddressCheck);
    
      if ($longIPAddressCheck > $firstIP && $longIPAddressCheck < ($firstIP + $NetworkLength))
      {
        return "true";
      }
      else
      {
        return "false";
      }
    
    }

  2. #2

    Thread Starter
    Fanatic Member
    Join Date
    Sep 2005
    Posts
    540

    Re: Check if valid IP Address

    This is for longhand or shorthand subnet masks.

    Code:
    function checkIPAddress($ipAddressCheck, $networkAddress, $subnetMask)
    {
      $shorthandSubnet=convertSubnetToShorthand($subnetMask); //Remove this line if you want $subnetMask to take shorthand subnet inputs (eg $subnetMask="8"; for /8 (255.0.0.0)
      $subnetBin=(pow(2,32)-1)-(pow(2,32-$shorthandSubnet)-1);
      $firstIP=ip2long($networkAddress) & ($subnetBin);
      $NetworkLength=pow(2,32-$shorthandSubnet)-1;
      $longIPAddressCheck = ip2long($ipAddressCheck);
    
      if ($longIPAddressCheck > $firstIP && $longIPAddressCheck < ($firstIP + $NetworkLength))
      {
        return "true";
      }
      else
      {
        return "false";
      }
    
    }
    
    function convertSubnetToShorthand($subnetMask)
    {
    
      $subnetOctets=explode(".", $subnetMask, 4);
      $reconcatinateSubnetMaskCount="";
    
      for ($octetIndex = 0; $octetIndex <= 3; $octetIndex++)
      {
        $subnetBinaryIndex[$octetIndex]=decbin($subnetOctets[$octetIndex]);
        $reconcatinateSubnetMaskCount=$reconcatinateSubnetMaskCount . $subnetBinaryIndex[$octetIndex];
      }
      
      return substr_count($reconcatinateSubnetMaskCount, "1");
    
    }

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width