PHPMost programming languages support IPv6 in some way or another since the dawn of IPv6. But how simple is it actually, to use IPv6 in your code? This is the first article in a series of articles where I’ll show you how each language handles IPv6, starting with PHP.

One of the first things you want to do is connect to an IPv6 address.

$fp = fsockopen('::1', 80);
if (!is_resource($fp)){
  // Error handling.

But this may fail if there is no IPv6 support. So to do it properly you would use something like:

$fp = fsockopen('::1', 80);
if (!is_resource($fp)) $fp = fsockopen('', 80);
if (!is_resource($fp)){
  // Error handling.

As seen above we simply try the IPv6 address and if it fails we retry in IPv4.

Listening on a port is quite the same as connecting to one in PHP. On most operating systems, listening on [::] is supported, even if you do not have IPv6 connectivity. However if someone happens to disable IPv6 or use an older version we need a fall back.

Here is an example with fallback to IPv4:

$errno = 0;
$errmsg = '';
$socket = stream_socket_server('tcp://[::]:49000', $errno, $errmsg);
if ($errno != 0 || !is_resource($socket))
  $socket = stream_socket_server('tcp://', $errno, $errmsg);
if ($errno != 0 || !is_resource($socket)){
  // Error handling

No obvious obstacles or strange behaviors so far.

Resolving IPs to names in PHP usually happens with the following two functions:

echo gethostbyname('').PHP_EOL;
echo gethostbyaddr(gethostbyname('')).PHP_EOL;

Which would output something like:

This looks correct at first glance … but wait … its IPv4!

The problem is that gethostbyname() always returns an IPv4 address, so we make our own:

function getHostByName6($input){
  $temp = dns_get_record($input, DNS_AAAA);
  if (isset($temp[0]['ipv6']))
    return $temp[0]['ipv6'];
  return false;

echo getHostByName6('').PHP_EOL;
echo gethostbyaddr(getHostByName6('')).PHP_EOL;

Which outputs:



Aside from that one minor detail with dns lookups, PHP seems to be able to handle it with ease.