In PHP, resolving a hostname or Fully Qualified Domain Name (FQDN) to an IP address is a common requirement in networked applications. This process involves converting a domain name, such as example.com, into its associated IP address. PHP offers built-in functions that handle this task efficiently.
The gethostbyname() function is typically used to convert a hostname into its IPv4 address. It provides a direct way to obtain a single IP address for a given domain. For scenarios where multiple IP addresses are associated with a hostname, the gethostbynamel() function returns an array of all available IPv4 addresses.
To support both IPv4 and IPv6 addresses, the dns_get_record() function is used. This function allows you to retrieve specific types of DNS records, such as A (IPv4) and AAAA (IPv6) records. These functions provide the necessary tools to manage DNS resolutions in PHP applications.
Steps to resolve a hostname to an IP address using PHP
- Use gethostbyname() to resolve a hostname or FQDN to an IPv4 address.
$hostname = "example.com"; $ip_address = gethostbyname($hostname); echo "IP Address for $hostname: " . $ip_address;
- If you need to retrieve multiple IP addresses, use gethostbynamel().
$hostname = "example.com"; $ip_addresses = gethostbynamel($hostname); if ($ip_addresses !== false) { foreach ($ip_addresses as $ip) { echo "IP Address: " . $ip . "\n"; } } else { echo "Failed to resolve hostname."; }
- To resolve both IPv4 and IPv6 addresses, use dns_get_record() and specify the desired DNS record type.
$hostname = "example.com"; $dns_records = dns_get_record($hostname, DNS_A + DNS_AAAA); foreach ($dns_records as $record) { if ($record['type'] === 'A' || $record['type'] === 'AAAA') { echo "IP Address: " . $record['ip'] . "\n"; } }

Mohd Shakir Zakaria is a cloud architect with deep roots in software development and open-source advocacy. Certified in AWS, Red Hat, VMware, ITIL, and Linux, he specializes in designing and managing robust cloud and on-premises infrastructures.
Comment anonymously. Login not required.