Validate IP Address

Description: Checks to make sure a given IP address fits the standard format.
Tested Platform: PHP 5
Language: PHP
// IsIPValid: Determines if the IP address passed in is proper format.
// Expects: Nothing but an IP address
// Returns: True or false if IP is valid or not.
function isIPValid($ip)
{
     if (preg_match("/^(d{1,3}).(d{1,3}).(d{1,3}).(d{1,3})$/",$ip)) {
          $parts = explode(".",$ip);

          foreach ($parts as $ip_parts) {
               if (intval($ip_parts) > 255 || intval($ip_parts) < 0) { 
                    return false; 
               }
          }
          return true;
     }
     return false; 
}

Submitted: December 24, 2012

Return to the snippets listing