WP
36 0
Asked
Updated
Viewed
8.8k times

I am trying to get the IPv6 address of a hostname with PHP. For example:

// Compressed
$IPv6 = "2001:4998:c:a06::2:4008";

// Expanded
$IPv6 = "2001:4998:000c:0a06:0000:0000:0002:4008";

I first get the hostname by:

$hostname = gethostbyname("2001:4998:c:a06::2:4008"); // ---> ir1.fp.vip.gq1.yahoo.com

or

$hostname = gethostbyname("2001:4998:000c:0a06:0000:0000:0002:4008"); // ---> ir1.fp.vip.gq1.yahoo.com

Whether I use the compressed or full version of IPv6 I get the same hostname. Now I use the hostname to get the IP address:

$ipaddress = gethostbyaddr("ir1.fp.vip.gq1.yahoo.com"); // ---> 206.190.36.45

This is the IPv4 address. I find the DNS_AAAA record by:

$recordAAAA = dns_get_record("ir1.fp.vip.gq1.yahoo.com", DNS_AAAA);

Which provides me the output:

Array
(
    [0] => Array
        (
            [host] => ir1.fp.vip.gq1.yahoo.com
            [class] => IN
            [ttl] => 300
            [type] => AAAA
            [ipv6] => 2001:4998:c:a06::2:4008
        )
)

I can definitely see the IPv6 compressed address. Having to use the DNS_AAAA record is not very efficient.

Is there any way to use the gethostbyaddr() function somehow to get the IPv6 address? Or what is the most efficient way to get the IPv6 address from the hostname?

add a comment
1

1 Answer

  • Votes
  • Oldest
  • Latest
Answered
Updated

I did a little research into this and if you want to stick with only using PHP functions then I think you already have the most efficient way. For convenience, I converted this into a reusable function:

/**
 * Get the IPV6 address from a hostname
 *
 * @param string $hostname
 * @return string|null If no IPV6 address is found it will return null
 */
function getIPv6hostbyaddr($hostname): ?string
{
    $record = dns_get_record($hostname, DNS_AAAA);

    return $record[0]['ipv6'] ?? null;
}

echo getIPv6hostbyaddr("ir1.fp.vip.gq1.yahoo.com"); // --> 2001:4998:c:a06::2:4008
add a comment
0