Well this may not be new to you all, but still, when I was on the lookout how I could validate an ip address, all the regular expression techniques either failed on valid addresses or bloated too much. The out come was wrote a piece of code which may help others if this is correct, in its way. Not sure, since most of the addresses which I tested against the other validation methods, and failed or non valid ones which passed were blocked here.
Still I am not the ultimate, if you have better suggestions than the code given here, please do so.
function is_ipaddress($string){
$parts = explode('.', $string);
if(count($parts) !== 4) return false;
foreach($parts as $pos => $tval){
$val = intval($tval);
if($tval !== (string)$val)
return false;
if(($pos == 0 or $pos == 3) && ($val < 1 or $val > 254))
return false;
elseif($val < 1 or $val > 255)
return false;
}
return true;
}
It should be noted that any IP address though valid, having the last dotted decimal equal to 0 (zero) will be a network address and not a host address. Similarly that which has 255 would be a broadcast address and not a valid host address. I have not done any bench marks, but having an inclination towards accuracy than performance, this would be better than the regexp methods. Since validating an IP address is not possible through a straight simple expression.