PHP Regular Expression从/ etc / hosts获取IP地址

时间:2010-08-12 16:16:38

标签: php regex hosts

我正在编写一个PHP脚本,通过Telnet自动配置设备,我需要从/ 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地址。

1 个答案:

答案 0 :(得分: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

相关问题