Detecting IPv6 In a Web Page

From SixXS Wiki
Jump to: navigation, search

If you wish to add detection of whether your site visitor is using IPv6 or IPv4, then the examples below will allow you to do so. Assuming that your web server is running on the local machine, then you can test your page by either using http://[::1]/ or http://127.0.0.1/ ,adding port number as necessary. Note that to use IPv6 with Apache2 (Apache does not support IPv6), you will need to make sure that the option was specified as part of the build.

PHP

The following example is a slightly reduced version of the example, taken from 'Sample usage of IPv6 and IPv4 with PHP':

class ipv6 {
   function get_ip() {
      return getenv("REMOTE_ADDR");
   }
   function isIPv6($ip = "") {
      if ($ip == "") {
         $ip = ipv6::get_ip();
      }
      if (substr_count($ip,":") > 0 && substr_count($ip,".") == 0) {
         return true;
      } else {
         return false;
      }
   }
}

$remoteIP= $_SERVER['REMOTE_ADDR'];

if ( ipv6::isIPv6($remoteIP) ) {
   // do something if visitor is using IPv6
} else {
   // do something if visitor is using IPv4
}

PHP - Alternative, using filter_var

The following is a modified version of the above, using filter_var.

class ipv6 {
   public static function get_ip() {
      return getenv("REMOTE_ADDR");
   }
   public static function isIPv6($ip = false) {
      $ip = (!$ip) ? ipv6::get_ip() : $ip;
      return filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6);
   }
}

if ( ipv6::isIPv6() ) {
   // do something if visitor is using IPv6
} else {
   // do something if visitor is using IPv4
}

PHP - Ultra Short Version

echo "You are connected using: ";
echo (strstr($_SERVER("REMOTE_ADDR"), ".")) ? "IPv4" : "IPv6" ;

Java

The following code example is for an HttpServlet:

public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
   String remoteAddr = req.getRemoteAddr();
   InetAddress inetAddress = InetAddress.getByName(remoteAddr);
   if ( inetAddress instanceof Inet6Address ) {    
      // do something if visitor is using IPv6
   } else {
     // do something if visitor is using IPv4
   }
}