Search code examples
phpnetwork-programmingsyntaxshell-execmac-address

Get MAC address from client's machine


I'm new to this, and I did some searching, but most of the answers have the same results: the MAC address output is shown as "Found."

My code is below:

$ip = $_SERVER['REMOTE_ADDR'];
$mac=shell_exec("arp -a ".$ip);
$mac_string = shell_exec("arp -a $ip");
$mac_array = explode(" ",$mac_string);
$mac = $mac_array[3];

if(empty($mac)) {
   die("No mac address for $ip not found");
}

echo($ip." - ".$mac);

Solution

  • Ah, the old exec() vs shell_exec() vs passthru() question.

    To see what command is actually being run, and what the system is actually returning, use exec(), and pass it an int and an array as its 2nd and 3rd params respectively, then var_dump() them both after running the command.

    For example:

    $cmd = "arp -a " . $ip;
    $status = 0;
    $return = [];
    exec($cmd, $return, $status);
    var_dump($status, $return);
    die;
    

    If everything went OK, then $status should be zero and $return may or may not be empty. However if $status is non-zero then pay attention to what the value of $return is, as this will be what your system is telling you is happening when it tries to run your command.

    Protip: Pass exec() the full path to arp as-in:

    #> which arp
    /usr/sbin/arp
    
    $cmd = "/usr/sbin/arp -a" . $ip;
    

    Also, bear in mind, depending on where the command is being run, REMOTE_ADDR may not return anything useful. There are several other ways of obtaining an IP address, which are especially useful if the IP address you need is behind some sort of proxy.