#學志#[jsp&&php]獲取客戶機mac地址

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

結果:


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章