php realization obtains the LAN all user's computer IP and the host name and mac address complete example

  • 2021-07-07 06:54:56
  • OfStack

The example of php described in this paper can obtain the IP, host name and mac address of all users in LAN, which is of reference value to php programmers. The complete code is as follows:


<?php
$bIp = gethostbyname($_ENV['COMPUTERNAME']); // Get the local area network of this machine IP
echo " Native machine IP : ",$bIp,"\n";
echo " Native Hostname: ",gethostbyaddr($bIp),"\n\n\n"; //gethostbyaddr  Function can be based on LAN IP Get the host name 
// Default gateway IP
list($ipd1,$ipd2,$ipd3) = explode('.',$bIp);
$mask = $ipd1 . "." . $ipd2 . "." . $ipd3 ;
exec('arp -a',$aIp); // Gets other in the LAN IP
foreach( $aIp as $ipv) {
 if(strpos($ipv,' Interface ') !== false) {//1 Below the IP Is it in the current LAN   Instead of other types   Can be found in cmd Next test 1 Give an order 
 $bool = false;
 preg_match('/(?:(?:25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d)))\.){3}(?:25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d)))/',$ipv,$arr);
 if(strcmp($arr[0],$bIp) == 0) {
  $bool = true;
 }
 } else {
 if($bool) {
  $str = preg_replace('/\s+/', '|', $ipv);
  $sArr = explode('|',$str);
  if($sArr[1] == 'Internet' || empty($sArr[1])) {
  continue;
  }
  // Remove the default gateway 
  if(strcmp($mask . ".1", $sArr[1]) == 0) {
  continue;
  }
  // Remove the same gateway 255 Adj. IP
  if(strcmp($mask . ".255", $sArr[1]) == 0) {
  continue;
  }
  // Remove multicast IP
  list($cIp) = explode('.', $sArr[1]);
  if($cIp >= 224 && $cIp <= 239) {
  continue;
  }
  echo "IP Address: |",$sArr[1],"|\n";
  echo "MAC Address: ",$sArr[2],"\n";
  echo " Hostname: ",gethostbyaddr($sArr[1]),"\n";
  echo "\n\n";
 }
 }
}

This program is running in cli mode, and it should also be possible on the browser
php obtains the user's ip function in LAN, mainly using exec function of php and arp-a command of window
Among them, getting native IP: gethostbyname ($_ ENV ['COMPUTERNAME']) is different from the previous writing, and interested friends can continue to study it in depth.
The Get Hostname function: gethostbyaddr (IPd) is also powerful.


Related articles: