PublicclassMacUtils{//这个方法运行时间太长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};//这个命令运行的时间很长,大概有10秒左右,整个程序就这的运行时间最长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;}}