Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IPV4 vs. IPV6 PHP Function

Tags:

php

ipv6

ipv4

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?

like image 305
J Johnson Avatar asked Jun 11 '26 10:06

J Johnson


2 Answers

PHP => 5.2 has a "built-in" approach to do this using filter_var

Your function could look like this:

function isIPv6($ip) {

   if(filter_var($ip, FILTER_VALIDATE_IP)) {

       if(filter_var($ip, FILTER_FLAG_IPV6)) {
          //It is IPv6 indeed.
        } else {
          //It is IPv4
       }

   } else {
      // NOT VALID IP
   }

}
like image 66
Ares Avatar answered Jun 13 '26 00:06

Ares


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;
  }
}

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!