문제

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
    }
}
도움이 되었습니까?

해결책

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 />';
        }
    }
?>
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top