Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

PHP Network gethostbyaddr() Function



The PHP Network gethostbyaddr() function is used to find the host name of an Internet host based on its IP address. It is useful when you want to determine which domain name belongs to a particular IP address. The function just takes as input the host's IP address, $ip. After successful completion, the host name is returned.

If the IP cannot be resolved to a host name, it returns the original IP address. If the input is corrupted or incorrect, it returns false. This function could be helpful in network building or server-side applications. It helps tasks like reverse DNS lookups. Make sure the input IP address is correctly verified to avoid errors.

Syntax

Below is the syntax of the PHP Network gethostbyaddr() function −

string gethostbyaddr ( string $ip )

Parameters

This function accepts $ip parameter which is a host IP address.

Return Value

The gethostbyaddr() function returns the Host Name if it is successful; if unsuccessful, return the unchanged IP address; and if the input is invalid, return FALSE.

PHP Version

First introduced in core PHP 4, the gethostbyaddr() function continues to function easily in PHP 5, PHP 7, and PHP 8.

Example 1

Here is the basic example of the PHP Network gethostbyaddr() function to get the host name of the given IP address. It demonstrates how to retrieve the host name of a known IP address.

<?php
   // Basic example 
   $ip = "8.8.8.8"; 
   $host = gethostbyaddr($ip);

   echo $host ? "Host name: $host" : "Unable to resolve hostname";
?>

Output

Here is the outcome of the following code −

Host name: dns.google

Example 2

This example adds error handling for invalid or malformed IP addresses. It ensures input is validated before using the gethostbyaddr() function.

<?php
   // Invalid IP address for testing
   $ip = "8.8.9";

   if (filter_var($ip, FILTER_VALIDATE_IP)) {
      $host = gethostbyaddr($ip);
      echo $host ? "Host name: $host" : "Unable to resolve hostname";
   } else {
      echo "Invalid IP address provided.";
   }
?> 

Output

This will generate the below output −

Invalid IP address provided.

Example 3

Now in the below code we will use an array of IP addresses and use the gethostbyaddr() function to get the host name of each and every IP address given in the array mentioned with the help of a loop.

<?php
   // Array of IPs
   $ips = ["8.8.8.8", "8.8.4.4", "invalid-ip"]; 
   
   foreach ($ips as $ip) {
      if (filter_var($ip, FILTER_VALIDATE_IP)) {
         $host = gethostbyaddr($ip);
         echo "IP: $ip => Host: " . ($host ?: "Unresolved") . PHP_EOL;
      } else {
         echo "Invalid IP: $ip" . PHP_EOL;
      }
   }
?> 

Output

This will create the below output −

IP: 8.8.8.8 => Host: dns.google
IP: 8.8.4.4 => Host: dns.google
Invalid IP: invalid-ip
php_function_reference.htm
Advertisements