IPv6 validation

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



Hello community,

I have been working with alot of IPv6 lately.

Now i was wondering of what there might be the best way to validate an IPv6
address.

Couldn't think of any working regexp, since even ::1 or :: is valid
(localhost), so i tried it the following way:

<?php
//RFC 4291
//http://tools.ietf.org/html/rfc4291
function validate_ipv6($value) {
 if (substr_count($value, ":") < 2) return false; // has to contain ":" at
least twice like in ::1 or 1234::abcd
 if (substr_count($value, "::") > 1) return false; // only 1 double colon
allowed
 $groups = explode(':', $value);
 $num_groups = count($groups);
 if (($num_groups > 8) || ($num_groups < 3)) return false; // 3-8 groups of
0-4 digits (1 group has to be at leas 1 digit)
 $empty_groups = 0;
 foreach ($groups as $group) {
  $group = trim($group);
  if (!empty($group) && !(is_numeric($group) && ($group == 0))) {
  if (!preg_match('#([a-fA-F0-9]{0,4})#', $group)) return false;
  } else ++$empty_groups;
 }
 return ($empty_groups < $num_groups) ? true : false; // the unspecified
address :: is not valid in this case
}
var_dump(validate_ipv6("::")); // false (wanted result)
var_dump(validate_ipv6("::1")); // true
var_dump(validate_ipv6("1234::abcd")); // true
var_dump(validate_ipv6("2001:DB8:0:0:8:800:200C:417A")); // true
var_dump(validate_ipv6("0:0:0:0:0:0:0:1")); // true
var_dump(validate_ipv6("0:0:0:0:0:0:0:0")); // false (wanted result)
var_dump(validate_ipv6("0000:0000:0000:0000:0000:0000:0000:0000")); // false
(wanted result)
var_dump(validate_ipv6("2001:0DB8:0000:CD30:0000:0000:0000:0000")); // true
var_dump(validate_ipv6("FF01:0:0:0:0:0:0:101")); // true
var_dump(validate_ipv6("bananas")); // false
var_dump(validate_ipv6("1:2:3:4:5:6:7:8:9")); // false
?>

anybody with better ideas?

Yeti

[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux