2

我正在编写一个通过 Telnet 自动配置设备的 PHP 脚本,我需要从 /etc/hosts 获取一些 IP 地址

我只需要它来获取 IP 地址,然后根据主机名将其分配给一个变量。例子:

192.168.1.50 machine
192.168.1.51 printer
192.168.1.52 sigpad

PHP 脚本应该是这样的:

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

当然,我的/etc/hosts文件是不同的,但你会从我的例子中得到想法。然后,我将能够将此 PHP 脚本包含到我们现有的任何程序中,并使用变量而不是硬编码的 IP 地址。

4

1 回答 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;
    }
}

例子:

echo ipFromEtcHosts('ip6-mcastprefix');

ff00::0.

于 2010-08-12T16:26:48.493 回答