tags:

views:

44

answers:

1

I'm writing a PHP script that autoconfigures a device over Telnet, and I need to grab some IP addresses from /etc/hosts

I need it to grab the IP address only, and assign it to a variable based on the hosts name. Example:

192.168.1.50 machine
192.168.1.51 printer
192.168.1.52 sigpad

The PHP script should be like this:

$machineip = "192.168.1.50";
$printerip = "192.168.1.51";
$sigpadip = "192.168.1.52";

Of course, my /etc/hosts file is different, but you'll get the idea from my example. I'll then be able to include this PHP script to any of our existing programs, and use the variables instead of hardcoded IP addresses.

+1  A: 
function ipFromEtcHosts($host) {
    foreach (new SplFileObject('/etc/hosts') as $line) {
        $d = preg_split('/\s/', $line, -1, PREG_SPLIT_NO_EMPTY);
        if (empty($d) || substr(reset($d), 0, 1) == "#")
           continue;
        $ip = array_shift($d);
        $hosts = array_map('strtolower', $d);
        if (in_array(strtolower($host), $hosts))
            return $ip;
    }
}

Example:

echo ipFromEtcHosts('ip6-mcastprefix');

gives ff00::0.

Artefacto
Can't upvote yet, but that worked perfectly! Thank you!
Mistiry