Search code examples
phpipv6ipv4

IPV4 vs. IPV6 PHP Function


I've been reading about how to determine whether an IP is IPv4 or IPv6 and it seems obvious to me that the thing to look for is whether there is a colon. However, then you have IPv4–mapped IPv6 addresses and IPv4–compatible IPv6 addresses. It seems to me that these types of addresses have both colons and periods, so instead of solutions that look for whether there is no ::ffff at the beginning of the string, why not just do this:

function isIPv6($ip) {
  if(strpos($ip, ":") !== false && strpos($ip, ".") === false) {
     return true;
  }
  return false;
}

EDIT: Am I missing something or would this function work properly in all cases?


Solution

  • From IBM:

    An IPv6 address can have two formats:
    
        Normal - Pure IPv6 format
        2001 : db8: 3333 : 4444 : 5555 : 6666 : 7777 : 8888
        Dual - IPv6 plus IPv4 formats
        2001 : db8: 3333 : 4444 : 5555 : 6666 : 1 . 2 . 3 . 4
    

    You function only validating Pure format of IPv6. I also suggest to use FILTER_FLAG_IPV4 or FILTER_FLAG_IPV6

    function isIPv6($ip) {
      if(strpos($ip, ":") !== false && strpos($ip, ".") === false) {
         return true; //Pure format
      }
      elseif(strpos($ip, ":") !== false && strpos($ip, ".") !== false){
        return true; //dual format
      }
      else{
      return false;
      }
    }