user5184664
user5184664

Reputation:

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

Upvotes: 1

Views: 19087

Answers (2)

thphoenix
thphoenix

Reputation: 191

Guess I could take this script a step further.. remember, only works on your local network. will return false if not able to get.

function GetMAC() { 
    $cmd = "arp -a " . $_SERVER["REMOTE_ADDR"]; 
    $status = 0; 
    $return = []; 
    exec($cmd, $return, $status); 
    if(isset($return[3])) return strtoupper(str_replace("-",":",substr($return[3],24,17))); 
    return false; 
}

Upvotes: 1

theruss
theruss

Reputation: 1746

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.

Upvotes: 3

Related Questions