Home >Backend Development >PHP Tutorial >How Can I Retrieve Connected Clients' MAC and IP Addresses Using PHP?
In PHP, obtaining the MAC and IP addresses of connected clients requires different approaches due to varying availability of this information.
The server's IP address is readily available through $_SERVER['SERVER_ADDR']. As for the MAC address, it can be retrieved by parsing the output of commands like netstat -ie (Linux) or ipconfig /all (Windows).
The client's IP address can be obtained from $_SERVER['REMOTE_ADDR'].
Determining the client's MAC address in PHP is challenging, as it is generally not accessible to the server except when clients reside on the same Ethernet segment.
If clients reside on the same LAN, parsing the output of arp -n (Linux) or arp -a (Windows) can provide the MAC address. Here's an example in PHP using backticks:
<br>$ipAddress=$_SERVER['REMOTE_ADDR'];<br>$macAddr=false;</p> <h1>run the external command, break output into lines</h1> <p>$arp=arp -a $ipAddress;<br>$lines=explode("n", $arp);</p> <h1>look for the output line describing our IP address</h1> <p>foreach($lines as $line)<br>{<br> $cols=preg_split('/s /', trim($line));<br> if ($cols[0]==$ipAddress)<br> {</p> <pre class="brush:php;toolbar:false"> $macAddr=$cols[1];
}
}
However, if clients are not on the same LAN, retrieving the MAC address is not possible through PHP without additional means of information transmission from the client.
The above is the detailed content of How Can I Retrieve Connected Clients' MAC and IP Addresses Using PHP?. For more information, please follow other related articles on the PHP Chinese website!