2

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.

2
  • If those entries are in your /etc/hosts your programs can address them by name already. Commented Aug 12, 2010 at 16:22
  • True, but our other programs need to know the actual IP addresses, as it includes them in reporting emails and databases. Commented Aug 12, 2010 at 20:52

1 Answer 1

2
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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.