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

结果:

PS:只能获取本机Mac地址,无法再服务端获取客户机的Mac地址。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 217,185评论 6 503
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,652评论 3 393
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 163,524评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,339评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,387评论 6 391
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,287评论 1 301
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,130评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,985评论 0 275
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,420评论 1 313
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,617评论 3 334
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,779评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,477评论 5 345
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,088评论 3 328
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,716评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,857评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,876评论 2 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,700评论 2 354

推荐阅读更多精彩内容