Hostnames can publish both IPv4 and IPv6 addresses as DNS resource records. PHP can query those records directly while keeping the address families distinguishable for application-specific handling.
The dns_get_record() function returns structured resource-record rows. Limiting the request to DNS_A and DNS_AAAA avoids unrelated records while exposing IPv4 values through the ip field and IPv6 values through ipv6.
DNS answers are snapshots rather than permanent mappings. Authoritative record changes and cached record lifetimes can change the returned set over time, so use a fully qualified hostname and handle an empty answer explicitly.
Related: Get a hostname from a URL using PHP
Tool: DNS Record Lookup
<?php function resolveHostnameToAddresses(string $hostname): array { $records = dns_get_record($hostname, DNS_A | DNS_AAAA); if ($records === false) { throw new RuntimeException("DNS query failed for {$hostname}"); } $addresses = []; return $addresses; }
dns_get_record() uses the resolver available to the running PHP process. It does not query an arbitrary name server selected by the script.
foreach ($records as $record) { if ($record['type'] === 'A' && isset($record['ip'])) { $addresses[] = [ 'type' => 'A', 'address' => $record['ip'], ]; } if ($record['type'] === 'AAAA' && isset($record['ipv6'])) { $addresses[] = [ 'type' => 'AAAA', 'address' => $record['ipv6'], ]; } } if ($addresses === []) { throw new RuntimeException("No A or AAAA records found for {$hostname}"); } return $addresses;
The record type selects the matching address field. An A row uses ip, while an AAAA row uses ipv6.
$hostname = trim($argv[1] ?? ''); if ($hostname === '') { fwrite(STDERR, "Usage: {$argv[0]} <hostname>" . PHP_EOL); exit(1); } try { $addresses = resolveHostnameToAddresses($hostname); } catch (RuntimeException $exception) { fwrite(STDERR, $exception->getMessage() . PHP_EOL); exit(1); } foreach ($addresses as $entry) { echo $entry['type'], ': ', $entry['address'], PHP_EOL; }
The record label preserves the address family until the caller applies an IPv4 or IPv6 connection policy. DNS answer order is not an application preference rule.
$ php hostname-to-ip.php missing-host.invalid. No A or AAAA records found for missing-host.invalid.
The trailing dot makes the test name absolute, so a local DNS search suffix cannot extend it.
$ php hostname-to-ip.php iana.org A: 192.0.43.8 AAAA: 2001:500:88:200::8
The exact records and their order can change when the authoritative zone or resolver cache changes.