Search code examples
phpiphostgethostbyname

PHP - Retrieving IPs from host names


I am retrieving values from a table field and appending a string to it to get a list of host names. I would then like to loop through all the host names and return the IP for each.

The following code gets my host names:

$sql = "select * from table order by col1 asc";

$q = mysql_query($sql) or die(mysql_error() ." " . $sql);

// Loop through table and append .zzz to each col1.
while ($r = mysql_fetch_array($q)) {

    $host_name = $r['col1']. ".zzz" . " ";

    //echo $host_name;
}

The above code works as it should, but I am unsure how to retrieve the IPs for each host name. I have been trying gethostbyname but can't get it to work correctly. I know I have to loop through the host name values. Would I use a foreach loop? I have tried that and can't get it working. Can someone give me some pointers please.

I have tried the following but it doesn't return anything:

$host_name_ip = $host_name;
foreach ($host_name_ip as $name) {
    $ip = gethostbyname($name);
    echo '<li>' . $ip. '</li>';
}

I have also tried this... again, nothing:

foreach($host_name as $url) {
    $ip = gethostbyname(trim($url)); 
}

echo $ip;

Thanks. :)


Solution

  • You are overwriting the value of $host_name in your initial loop. Change it to be an array and your foreach will work.

    while ($r = mysql_fetch_array($q)) {
        $host_name[] = $r['col1']. ".zzz";
    }
    

    To print the host name and it's address in your loop use:

    foreach ($host_name_ip as $name) {
        $ip = gethostbyname($name);
        echo '<li>' . $name . ' is at address ' . $ip. '</li>';
    }
    

    You don't even need to store the names in an array. Just do everything you need in your while loop.

    while ($r = mysql_fetch_array($q)) {
        $ip = gethostbyname($r['col1']. ".zzz");
        echo '<li>' . $r['col1']. '.zzz' . ' is at address ' . $ip. '</li>';
    }