Problem with getting information of currently configured network interfaces on Linux
I am encountering a problem with string formatting while trying to get only the names of currently configured network interfaces on a Linux Machine.
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. ?>
How can i get $arr of size=2 such that echo $arr[0]; //gives 'eth0' echo $arr[1]; //gives 'lo'
Thanks a lot
Update: I thing following command will do the magic for me
ifconfig | grep -o -e "[a-z][a-z]*[0-9]*[ ]*Link" | perl -pe "s|^([a-z]*[0-9]*)[ ]*Link|\1|"
but i am doing something wrong while executing it from a php file because the browser does not show anything.
<?php
$temp = shell_exec("ifco开发者_开发技巧nfig | grep -o -e \"[a-z][a-z]*[0-9]*[ ]*Link\" | perl -pe \"s|^([a-z]*[0-9]*)[ ]*Link|\\1|\"");
echo $temp;
?>
Note that you should check the return value to be sure the call exited successfully, but it basically can be done with this:
exec('/sbin/ifconfig -s|awk \'{print $1}\'', $interfaces, $returnValue);
array_shift($interfaces);
Well, you can get rid of the whitespace for example this way:
explode(' ', trim(preg_replace('/\s+/', ' ', $temp)));
Note that on Linux you can get the info without executing an external command by reading from /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]);
}
精彩评论