phpgethostbyaddr

How to make no statement if not show hostname - gethostbyaddr


I try to make simple php script to show hostname using gethostbyaddr. Let pretend the ip xxx.xxx.xxx.4 will show the hostname and ip xxx.xxx.xxx.5 not show hostname. My question is, how do i make if no hostname statement? Thank you.

$ips = array("xxx.xxx.xxx.4","xxx.xxx.xxx.5");

foreach ($ips as $value) {
    if ($hostip = @gethostbyaddr( $value )) {
       echo "$hostip<br>";
    }   
    else {
       //show no hostname statement here
    }
}

Solution

  • According to the manual:

    Returns the host name on success, the unmodified ip_address on failure, or FALSE on malformed input.

    So you could do this:

    <?php
        $ips = array("xxx.xxx.xxx.4","xxx.xxx.xxx.5");
    
        foreach ($ips as $value) {
            $hostname = gethostbyaddr($value);
    
            if ($hostname === false) { //malformed input
                echo 'IP "' . $value . '" was malformed<br />';
            } else if ($hostname === $value) { //failure
                echo 'Hostname could not be found for "' . $value . '"<br />';
            } else { //success
                echo 'Hostname: ' . $hostname . '<br />';
            }
        }
    ?>