Question

I am getting output from my linux box running the ifconfig command. I do so by running the shell_exec command. I found an example but I can't seem to work further with it.

This is my current code.

public function get_network_interfaces() {

    // Run the command.
    $cmd_exec = shell_exec("/sbin/ifconfig");

    // Get the pattern.
    $pattern = '/inet addr:([\d]{1,3}\.[\d]{1,3}\.[\d]{1,3}\.[\d]{1,3})/';

    if (preg_match_all($pattern, $cmd_exec, $matches)) {
        $interfaces = $matches[1];
        return $interfaces;         
    }

}

The output of this (after foreach'ing) is simply; 192.168.1.1/127.0.0.1 because it has two network adapters, the output of ifconfig is;

eth0      Link encap:Ethernet  HWaddr 00:16:3e:38:b8:1c  
      inet addr:192.168.1.1  Bcast:192.168.1.255  Mask:255.255.255.0
      inet6 addr: 2a02:2308::216:3eff:fe38:b81c/64 Scope:Global
      inet6 addr: fe80::216:3eff:fe38:b81c/64 Scope:Link
      UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
      RX packets:10612623 errors:0 dropped:0 overruns:0 frame:0
      TX packets:151855 errors:0 dropped:0 overruns:0 carrier:0
      collisions:0 txqueuelen:1000 
      RX bytes:539434883 (514.4 MiB)  TX bytes:37861938 (36.1 MiB)
      Interrupt:30
lo        Link encap:Local Loopback  
      inet addr:127.0.0.1  Mask:255.0.0.0
      inet6 addr: ::1/128 Scope:Host
      UP LOOPBACK RUNNING  MTU:16436  Metric:1
      RX packets:6662 errors:0 dropped:0 overruns:0 frame:0
      TX packets:6662 errors:0 dropped:0 overruns:0 carrier:0
      collisions:0 txqueuelen:0 
      RX bytes:768641 (750.6 KiB)  TX bytes:768641 (750.6 KiB)

What I am trying to get is like, the names of the interfaces (eth0 and lo), along with the inet adds (which is working already) followed by RX bytes and TX bytes. If the name is too hard to get, so be it. But can anyone explain me how to get the RX bytes and TX bytes?

Thanks.

Was it helpful?

Solution

For the names of the interfaces, this should work:

$pattern = '/^(\w*)\s*Link encap.*$/';

For the RX and TX bytes:

$pattern = '/RX packets:(\d*) /';
$pattern = '/TX packets:(\d*) /';

And you should test in order to be sure you have all the information for every interface:

  1. Test for the name of the interface.
  2. Test for the IP number.
  3. Test for the RX byte.
  4. Test for the TX byte.

and when you have the four of them, then go for another cycle (for example with continue).

P.S. Be careful about the language you're using in your system, because with spanish you get "Paquetes RX:". Just to be sure, and in order to make your code more robust, you should try to make shell_exec to set environment variable LC_MESSAGES to en_us.utf-8 for example.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top