java实现获取用户的MAC地址
方法一:将本机地址与局域网内其他机器区分开来
/** *根据IP地址获取mac地址 *@paramipAddress127.0.0.1 *@return *@throwsSocketException *@throwsUnknownHostException */ publicstaticStringgetLocalMac(StringipAddress)throwsSocketException, UnknownHostException{ //TODOAuto-generatedmethodstub Stringstr=""; StringmacAddress=""; finalStringLOOPBACK_ADDRESS="127.0.0.1"; //如果为127.0.0.1,则获取本地MAC地址。 if(LOOPBACK_ADDRESS.equals(ipAddress)){ InetAddressinetAddress=InetAddress.getLocalHost(); //貌似此方法需要JDK1.6。 byte[]mac=NetworkInterface.getByInetAddress(inetAddress) .getHardwareAddress(); //下面代码是把mac地址拼装成String StringBuildersb=newStringBuilder(); for(inti=0;i<mac.length;i++){ if(i!=0){ sb.append("-"); } //mac[i]&0xFF是为了把byte转化为正整数 Strings=Integer.toHexString(mac[i]&0xFF); sb.append(s.length()==1?0+s:s); } //把字符串所有小写字母改为大写成为正规的mac地址并返回 macAddress=sb.toString().trim().toUpperCase(); returnmacAddress; }else{ //获取非本地IP的MAC地址 try{ System.out.println(ipAddress); Processp=Runtime.getRuntime() .exec("nbtstat-A"+ipAddress); System.out.println("===process=="+p); InputStreamReaderir=newInputStreamReader(p.getInputStream()); BufferedReaderbr=newBufferedReader(ir); while((str=br.readLine())!=null){ if(str.indexOf("MAC")>1){ macAddress=str.substring(str.indexOf("MAC")+9,str.length()); macAddress=macAddress.trim(); System.out.println("macAddress:"+macAddress); break; } } p.destroy(); br.close(); ir.close(); }catch(IOExceptionex){ } returnmacAddress; } }
我们再来看下方法二:
packagecom.alpha.test; importjava.io.BufferedReader; importjava.io.IOException; importjava.io.InputStream; importjava.io.InputStreamReader; importjava.io.LineNumberReader; publicclassGetMac{ /** *java获取客户端网卡的MAC地址 * *@paramargs */ publicstaticvoidmain(String[]args){ GetMacget=newGetMac(); System.out.println("1="+get.getMAC()); System.out.println("2="+get.getMAC("127.0.0.1")); } //1.获取客户端ip地址(这个必须从客户端传到后台): //jsp页面下,很简单,request.getRemoteAddr(); //因为系统的VIew层是用JSF来实现的,因此页面上没法直接获得类似request,在bean里做了个强制转换 //publicStringgetMyIP(){ //try{ //FacesContextfc=FacesContext.getCurrentInstance(); //HttpServletRequestrequest=(HttpServletRequest)fc //.getExternalContext().getRequest(); //returnrequest.getRemoteAddr(); //}catch(Exceptione){ //e.printStackTrace(); //} //return""; //} //2.获取客户端mac地址 //调用window的命令,在后台Bean里实现通过ip来获取mac地址。方法如下: //运行速度【快】 publicStringgetMAC(){ Stringmac=null; try{ Processpro=Runtime.getRuntime().exec("cmd.exe/cipconfig/all"); InputStreamis=pro.getInputStream(); BufferedReaderbr=newBufferedReader(newInputStreamReader(is)); Stringmessage=br.readLine(); intindex=-1; while(message!=null){ if((index=message.indexOf("PhysicalAddress"))>0){ mac=message.substring(index+36).trim(); break; } message=br.readLine(); } System.out.println(mac); br.close(); pro.destroy(); }catch(IOExceptione){ System.out.println("Can'tgetmacaddress!"); returnnull; } returnmac; } //运行速度【慢】 publicStringgetMAC(Stringip){ Stringstr=null; StringmacAddress=null; try{ Processp=Runtime.getRuntime().exec("nbtstat-A"+ip); InputStreamReaderir=newInputStreamReader(p.getInputStream()); LineNumberReaderinput=newLineNumberReader(ir); for(;true;){ str=input.readLine(); if(str!=null){ if(str.indexOf("MACAddress")>1){ macAddress=str .substring(str.indexOf("MACAddress")+14); break; } } } }catch(IOExceptione){ e.printStackTrace(System.out); returnnull; } returnmacAddress; } }
方法三,更精简一些
importjava.io.IOException; importjava.io.InputStreamReader; importjava.io.LineNumberReader; publicclassMACAddress{ Stringip; Stringmac; publicMACAddress(Stringip){ this.ip=ip; } publicMACAddress(){ this.ip="0.0.0.0"; } publicStringgetMac(){ try{ Processp=Runtime.getRuntime().exec("arp-n"); InputStreamReaderir=newInputStreamReader(p.getInputStream()); LineNumberReaderinput=newLineNumberReader(ir); p.waitFor(); booleanflag=true; StringipStr="("+this.ip+")"; while(flag){ Stringstr=input.readLine(); if(str!=null){ if(str.indexOf(ipStr)>1){ inttemp=str.indexOf("at"); this.mac=str.substring( temp+3,temp+20); break; } }else flag=false; } }catch(IOException|InterruptedExceptione){ e.printStackTrace(System.out); } returnthis.mac; } publicvoidsetIp(Stringip){ this.ip=ip; } }
最后要放大招了,小伙伴们看仔细哦
首先要说的是:本方法可以支持外网机器的mac地址获取。
以前弄了一个只能访问局域网。有防火墙就访问不了,但是这个不用担心了。
测试了百度的ip,已经可以获得mac地址
java通过ip获取mac地址-封ip封mac地址
importjava.io.BufferedReader; importjava.io.InputStreamReader; importjava.util.regex.Matcher; importjava.util.regex.Pattern; /** *获取MAC地址 *@author *2011-12 */ publicclassGetMacAddress{ publicstaticStringcallCmd(String[]cmd){ Stringresult=""; Stringline=""; try{ Processproc=Runtime.getRuntime().exec(cmd); InputStreamReaderis=newInputStreamReader(proc.getInputStream()); BufferedReaderbr=newBufferedReader(is); while((line=br.readLine())!=null){ result+=line; } } catch(Exceptione){ e.printStackTrace(); } returnresult; } /** * *@paramcmd第一个命令 *@paramanother第二个命令 *@return第二个命令的执行结果 */ publicstaticStringcallCmd(String[]cmd,String[]another){ Stringresult=""; Stringline=""; try{ Runtimert=Runtime.getRuntime(); Processproc=rt.exec(cmd); proc.waitFor();//已经执行完第一个命令,准备执行第二个命令 proc=rt.exec(another); InputStreamReaderis=newInputStreamReader(proc.getInputStream()); BufferedReaderbr=newBufferedReader(is); while((line=br.readLine())!=null){ result+=line; } } catch(Exceptione){ e.printStackTrace(); } returnresult; } /** * *@paramip目标ip,一般在局域网内 *@paramsourceString命令处理的结果字符串 *@parammacSeparatormac分隔符号 *@returnmac地址,用上面的分隔符号表示 */ publicstaticStringfilterMacAddress(finalStringip,finalStringsourceString,finalStringmacSeparator){ Stringresult=""; StringregExp="((([0-9,A-F,a-f]{1,2}"+macSeparator+"){1,5})[0-9,A-F,a-f]{1,2})"; Patternpattern=Pattern.compile(regExp); Matchermatcher=pattern.matcher(sourceString); while(matcher.find()){ result=matcher.group(1); if(sourceString.indexOf(ip)<=sourceString.lastIndexOf(matcher.group(1))){ break;//如果有多个IP,只匹配本IP对应的Mac. } } returnresult; } /** * *@paramip目标ip *@returnMacAddress * */ publicstaticStringgetMacInWindows(finalStringip){ Stringresult=""; String[]cmd={ "cmd", "/c", "ping"+ip }; String[]another={ "cmd", "/c", "arp-a" }; StringcmdResult=callCmd(cmd,another); result=filterMacAddress(ip,cmdResult,"-"); returnresult; } /** *@paramip目标ip *@returnMacAddress * */ publicstaticStringgetMacInLinux(finalStringip){ Stringresult=""; String[]cmd={ "/bin/sh", "-c", "ping"+ip+"-c2&&arp-a" }; StringcmdResult=callCmd(cmd); result=filterMacAddress(ip,cmdResult,":"); returnresult; } /** *获取MAC地址 *@return返回MAC地址 */ publicstaticStringgetMacAddress(Stringip){ StringmacAddress=""; macAddress=getMacInWindows(ip).trim(); if(macAddress==null||"".equals(macAddress)){ macAddress=getMacInLinux(ip).trim(); } returnmacAddress; } //做个测试 publicstaticvoidmain(String[]args){ System.out.println(getMacAddress("220.181.111.148")); } }