【问题标题】:Problem with getting information of currently configured network interfaces on Linux在 Linux 上获取当前配置的网络接口信息的问题
【发布时间】:2009-11-01 10:16:05
【问题描述】:

我在尝试仅获取 Linux 机器上当前配置的网络接口的名称时遇到了字符串格式问题。

1. <?php
2. $temp = shell_exec("/sbin/ifconfig | cut -b 1-10");
3. echo $temp;                           //Outputs: eth0 lo
4. $arr = explode(" ",$temp);
5. echo "First Location:".$arr[0];         //Outputs: eth0
6. echo "Second Location:".$arr[1];        //Outputs:    
7. echo count($a);                       //Outputs: 165
8. ?>

我怎样才能得到 size=2 的 $arr 这样 回声 $arr[0]; //给出'eth0' 回声 $arr[1]; //给出'lo'

非常感谢

更新: 我遵循命令将为我带来魔力

ifconfig | grep -o -e "[a-z][a-z]*[0-9]*[ ]*Link" | perl -pe "s|^([a-z]*[0-9]*)[ ]*Link|\1|"

但我在从 php 文件执行时做错了,因为浏览器没有显示任何内容。

<?php    
$temp = shell_exec("ifconfig | grep -o -e \"[a-z][a-z]*[0-9]*[ ]*Link\" | perl -pe \"s|^([a-z]*[0-9]*)[ ]*Link|\\1|\"");
echo $temp;
?>

【问题讨论】:

    标签: php linux


    【解决方案1】:

    请注意,您应该检查返回值以确保调用成功退出,但基本上可以这样做:

    exec('/sbin/ifconfig -s|awk \'{print $1}\'', $interfaces, $returnValue);
    array_shift($interfaces);
    

    【讨论】:

    • 不错。 :) 但此命令返回两个元素:1)eth0 和 2)Iface。什么是Iface。我在 shell 中运行 /sbin/ifconfig 时看不到任何 Iface。
    • 修复了错误,应该是array_shift(),而不是array_pop()。运行/sbin/ifconfig -s,你会发现问题出在哪里。
    • 是的,它是“接口”的缩写,谢谢一百万。该代码现在正在运行。 :D
    【解决方案2】:

    嗯,你可以通过这种方式去掉空格:

    explode(' ', trim(preg_replace('/\s+/', ' ', $temp)));
    

    请注意,在 Linux 上,您无需执行外部命令即可通过读取 /proc/net/dev 来获取信息。

    $lines = file('/proc/net/dev');
    $interfaces = array();
    for ($i = 2; $i < count($lines);  $i++) {
        $line = explode(':', $lines[$i]);
        $interfaces[] = trim($line[0]);
    }
    

    【讨论】:

    • 谢谢。从 /proc/net/dev 读取似乎是一个不错的方法,但它提供了太多信息。你能告诉我如何只能访问“当前配置”接口的名称吗?
    • 读取文件,分割行,忽略前两行,每行以:分割,取第一部分,修剪空白,添加到接口列表。
    猜你喜欢
    • 1970-01-01
    • 2010-10-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-16
    • 2015-08-22
    • 1970-01-01
    • 2020-01-29
    相关资源
    最近更新 更多