#学志#[jsp&&php]获取客户机mac地址

  • Post author:
  • Post category:php


jsp:

1、首先需要获取客户机的ip地址

String sip = request.getHeader("x-forwarded-for"); 
if (sip == null || sip.length() == 0 || "unknown".equalsIgnoreCase(sip)) { 
	sip = request.getHeader("Proxy-Client-IP"); 
} 
if (sip == null || sip.length() == 0 || "unknown".equalsIgnoreCase(sip)) { 
	sip = request.getHeader("WL-Proxy-Client-IP"); 
} 
if (sip == null || sip.length() == 0 || "unknown".equalsIgnoreCase(sip)) { 
	sip = request.getRemoteAddr(); 
} 
System.out.println(sip);

结果:

“`

127.0.0.1

“`

2、根据ip地址获得客户机的mac地址

在不同系统下的获取方式不同;

1)获得用户的操作系统:

String os = System.getProperty("os.name");  
System.out.println(os);

结果:

“`

Linux

“`

2)根据所在的系统进行mac地址的获取

     String macAddress = null;
     if(os.equals("Windows"))
     macAddress = getMacInWindows(ip).trim();
     else if(os.equals("Linux"))
     macAddress = getMacInLinux(ip).trim();
     return macAddress;

其中在windows获取的方法:

public static String getMacInWindows(final String ip){ 
     String result = ""; 
     String[] cmd = { 
         "cmd", 
         "/c", 
         "ping " + ip 
         }; 
     String[] another = { 
         "cmd", 
         "/c", 
         "arp -a"
         }; 
   
     String cmdResult = callCmd(cmd,another); 
     result = filterMacAddress(ip,cmdResult,"-"); 
   
     return result; 
   } 

在Linux获取的方法:

public static String getMacInLinux(final String ip){ 
     String result = ""; 
     String[] cmd = { 
         "/bin/sh", 
         "-c", 
         "ping " + ip + " -c 2 && arp -a"
         }; 
     String cmdResult = callCmd(cmd); 
     result = filterMacAddress(ip,cmdResult,":"); 
   
     return result; 
   } 

关键函数:

对结果进行分割获得mac地址;

/** 
   * 
   * @param ip 目标ip,一般在局域网内 
   * @param sourceString 命令处理的结果字符串 
   * @param macSeparator mac分隔符号 
   * @return mac地址,用上面的分隔符号表示 
   */
   public static String filterMacAddress(final String ip, final String sourceString,final String macSeparator) { 
     String result = ""; 
     String regExp = "((([0-9,A-F,a-f]{1,2}" + macSeparator + "){1,5})[0-9,A-F,a-f]{1,2})"; 
     Pattern pattern = Pattern.compile(regExp); 
     Matcher matcher = pattern.matcher(sourceString); 
     while(matcher.find()){ 
       result = matcher.group(1); 
       if(sourceString.indexOf(ip) <= sourceString.lastIndexOf(matcher.group(1))) { 
         break; //如果有多个IP,只匹配本IP对应的Mac. 
       } 
     }
   
     return result; 
   }

完整版代码:

java获取类:

package test;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
 
 
/**
* 获取MAC地址
* @author
* 2011-12
*/
public class GetMacAddress {
   public static String callCmd(String[] cmd) { 
     String result = ""; 
     String line = ""; 
     try { 
       Process proc = Runtime.getRuntime().exec(cmd); 
       InputStreamReader is = new InputStreamReader(proc.getInputStream()); 
       BufferedReader br = new BufferedReader (is); 
       while ((line = br.readLine ()) != null) { 
       result += line; 
       } 
     } 
     catch(Exception e) { 
       e.printStackTrace(); 
     } 
     return result; 
   }
    
   /** 
   * 
   * @param cmd 第一个命令 
   * @param another 第二个命令 
   * @return  第二个命令的执行结果 
   */
   public static String callCmd(String[] cmd,String[] another) { 
     String result = ""; 
     String line = ""; 
     try { 
       Runtime rt = Runtime.getRuntime(); 
       Process proc = rt.exec(cmd); 
       proc.waitFor(); //已经执行完第一个命令,准备执行第二个命令 
       proc = rt.exec(another); 
       InputStreamReader is = new InputStreamReader(proc.getInputStream()); 
       BufferedReader br = new BufferedReader (is); 
       while ((line = br.readLine ()) != null) { 
         result += line; 
       } 
     } 
     catch(Exception e) { 
       e.printStackTrace(); 
     } 
     return result; 
   }
    
    
    
   /** 
   * 
   * @param ip 目标ip,一般在局域网内 
   * @param sourceString 命令处理的结果字符串 
   * @param macSeparator mac分隔符号 
   * @return mac地址,用上面的分隔符号表示 
   */
   public static String filterMacAddress(final String ip, final String sourceString,final String macSeparator) { 
     String result = ""; 
     String regExp = "((([0-9,A-F,a-f]{1,2}" + macSeparator + "){1,5})[0-9,A-F,a-f]{1,2})"; 
     Pattern pattern = Pattern.compile(regExp); 
     Matcher matcher = pattern.matcher(sourceString); 
     while(matcher.find()){ 
       result = matcher.group(1); 
       if(sourceString.indexOf(ip) <= sourceString.lastIndexOf(matcher.group(1))) { 
         break; //如果有多个IP,只匹配本IP对应的Mac. 
       } 
     }
   
     return result; 
   }
    
    
    
   /** 
   * 
   * @param ip 目标ip 
   * @return  Mac Address 
   * 
   */
   public static String getMacInWindows(final String ip){ 
     String result = ""; 
     String[] cmd = { 
         "cmd", 
         "/c", 
         "ping " + ip 
         }; 
     String[] another = { 
         "cmd", 
         "/c", 
         "arp -a"
         }; 
   
     String cmdResult = callCmd(cmd,another); 
     result = filterMacAddress(ip,cmdResult,"-"); 
   
     return result; 
   } 
 
   /** 
   * @param ip 目标ip 
   * @return  Mac Address 
   * 
   */
   public static String getMacInLinux(final String ip){ 
     String result = ""; 
     String[] cmd = { 
         "/bin/sh", 
         "-c", 
         "ping " + ip + " -c 2 && arp -a"
         }; 
     String cmdResult = callCmd(cmd); 
     result = filterMacAddress(ip,cmdResult,":"); 
   
     return result; 
   } 
    
   /**
   * 获取MAC地址 
   * @return 返回MAC地址
   */
   public static String getMacAddress(String ip){
	 //判断操作系统
	 String os = System.getProperty("os.name");  
//	 System.out.println(os + " can't gunzip");  
	    
     String macAddress = null;
     if(os.equals("Windows"))
     macAddress = getMacInWindows(ip).trim();
     else if(os.equals("Linux"))
     macAddress = getMacInLinux(ip).trim();
     return macAddress;
   }
 
   //做个测试
   public static void main(String[] args) {      
     System.out.println("220.181.111.148's mac is "+getMacAddress("220.181.111.148"));
     System.out.println("127.0.0.1's mac is "+getMacAddress("127.0.0.1"));
   }
   
}

测试结果:

“`

220.181.111.148’s mac is

127.0.0.1’s mac is 74:25:8a:3c:6d:2f

“`

jsp文件:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page import="test.*" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
22222
<% 
String smac = "";
System.out.println(request);
String sip = request.getHeader("x-forwarded-for"); 
if (sip == null || sip.length() == 0 || "unknown".equalsIgnoreCase(sip)) { 
	sip = request.getHeader("Proxy-Client-IP"); 
} 
if (sip == null || sip.length() == 0 || "unknown".equalsIgnoreCase(sip)) { 
	sip = request.getHeader("WL-Proxy-Client-IP"); 
} 
if (sip == null || sip.length() == 0 || "unknown".equalsIgnoreCase(sip)) { 
	sip = request.getRemoteAddr(); 
} 
System.out.println(sip);
GetMacAddress gma = new GetMacAddress();
smac = gma.getMacAddress(sip);
session.setAttribute("smac", smac); 
System.out.println(smac);
%>
</body>
</html>

结果:

“`

org.apache.catalina.connector.RequestFacade@13f30260

127.0.0.1

74:25:8a:3c:6d:2f

“`

php:

<?php
class GetMacAddr{
    public $returnArray = array();
    public $macAddr;

    function GetMacAddr($os_type=null){
        if(is_null($os_type)) 
        	$os_type = PHP_OS;
        switch (strtolower($os_type)){
        case "linux":
            $this->forLinux();
            break;
        case "solaris":
            break;
        case "unix":
            break;
        case "aix":
            break;
        default:
            $this->forWindows();
            break;
        }
        $temp_array = array();
        foreach($this->returnArray as $value ){
            if(preg_match("/[0-9a-f][0-9a-f][:-]"."[0-9a-f][0-9a-f][:-]"."[0-9a-f][0-9a-f][:-]"."[0-9a-f][0-9a-f][:-]"."[0-9a-f][0-9a-f][:-]"."[0-9a-f][0-9a-f]/i", $value, $temp_array)){
                $this->macAddr = $temp_array[0];
                break;
            }
        }
        unset($temp_array);
        return $this->macAddr;
    }

    function forWindows(){
        @exec("ipconfig /all", $this->returnArray);
        if($this->returnArray)
            return $this->returnArray;
        else{
            $ipconfig = $_SERVER["WINDIR"]."system32ipconfig.exe";
            if (is_file($ipconfig))
                @exec($ipconfig." /all", $this->returnArray);
            else
                @exec($_SERVER["WINDIR"]."systemipconfig.exe /all", $this->returnArray);
            return $this->returnArray;
        }
    }

    function forLinux(){
        @exec("ifconfig -a", $this->returnArray);
        return $this->returnArray;
    }
}
//方法使用
$mac = new GetMacAddr(PHP_OS);
echo $mac->macAddr;
?>

结果:




版权声明:本文为httIsAWang原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。