Home > Code Snippets, Tips > function is_ipaddress

function is_ipaddress

April 10th, 2009 Leave a comment Go to comments

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);
count($parts) !== 4) return false;
$parts as $pos => $tval){
$val intval($tval);
$tval !== (string)$val)
$pos == or $pos == 3) && ($val or $val 254))
$val or $val 255)

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.

Categories: Code Snippets, Tips Tags:
  1. December 9th, 2009 at 15:39 | #1

    Please don’t use this function. It assumes everything is a /24 (which is completely untrue in today’s internet) and also side-steps completely IPv6 addressing. is a perfectly valid host address (part of for example.)

    This will probably work for most cases on someone’s home LAN, where wireless routers and the like support IPv4 only and give out /24’s by default – but anywhere else this will silently reject many perfectly valid IP addresses.

    Best regards,

  2. December 11th, 2009 at 09:00 | #2

    @Gareth Eason
    Thanks Garth, will see if I can modify the function in any way such that it will address the whole spectrum, but I don’t think the IPv6 ‘d be a concern.

  1. No trackbacks yet.

− five = one