The function of this function is to resolve a hostname to.
$ip = gethostbyname('gitbox.net');
echo $ip;
If the host name can be successfully parsed, it returns an IPv4 address in the form of a string (for example: 192.168.1.1 ). If parsing fails, the original host name string is returned.
Unlike the above function, gethostbynamel() returns an array of all IPv4 addresses corresponding to the hostname.
$ips = gethostbynamel('gitbox.net');
print_r($ips);
If the hostname cannot be resolved, false is returned. If successful, multiple IP addresses may be returned, such as multi-network card hosts, load balancing services and other scenarios.
aspect | gethostbyname | gethostbynamel |
---|---|---|
Return value type | String | Array or false |
Whether multiple IPs are supported | No, only one (first one) | Yes, returns all available IPv4 addresses |
IPv6 support | no | no |
Return on failure | Original host name string | false |
Recommended use | Simple check or logging | Obtain all A records, load balancing analysis, etc. |
Website monitoring or health check <br> If you just want to detect whether a domain name can be parsed normally, you can use gethostbyname() :
$ip = gethostbyname('gitbox.net');
if ($ip === 'gitbox.net') {
echo "DNS Analysis failed";
} else {
echo "DNS Successful analysis,IP: $ip";
}
Server multi-IP binding or distributed processing <br> If you need to obtain all IP addresses of a domain name, for example, in CDN, load balancing, or master-slave environments, you can use gethostbynamel() :
$ips = gethostbynamel('gitbox.net');
if ($ips === false) {
echo "Unable to obtain IP Address list";
} else {
foreach ($ips as $ip) {
echo "Discover IP:$ip\n";
}
}
Neither function supports IPv6 . If you need to support IPv6, use dns_get_record() and specify the type AAAA .
gethostbyname() only returns the first IP in the parsed result and cannot represent the access capability of the entire domain name.
These functions depend on the server's DNS configuration, and DNS timeout or resolution failure affects the results.
These two functions have been marked as deprecated in the PHP document. It is recommended to gradually use more flexible dns_get_record() instead.