Chris Chris - 1 year ago 358
PHP Question

Get MAC address from client's machine

im new to this and did some searching but moust of them has the same results...the mac output is shown as "Found"

my code as below:

$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);


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);

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

$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.