如何获得客户端的IP及MAC地址
如何获得客户端的IP及MAC地址
1、获得真实的IP地址
public static String getIpAddr(HttpServletRequest request) {
Stringip=request.getHeader("x-forwarded-for");
if(ip==null||ip.length()==0||"unknown".equalsIgnoreCase(ip)){
ip=request.getHeader("Proxy-Client-IP");
}
if(ip==null||ip.length()==0||"unknown".equalsIgnoreCase(ip)){
ip=request.getHeader("WL-Proxy-Client-IP");
}
if(ip==null||ip.length()==0||"unknown".equalsIgnoreCase(ip)){
ip=request.getRemoteAddr();
}
returnip;
}2、下面两个方法,是获得MAC地址。
public static String callCmd(String[] cmd) {
StringBuilderresult=newStringBuilder("");
Stringline="";
try{
Processproc=null;
for(Stringtmp:cmd){
proc=Runtime.getRuntime().exec(tmp);
proc.waitFor();
}
BufferedInputStreamin=newBufferedInputStream(proc.getInputStream());
BufferedReaderbr=newBufferedReader(newInputStreamReader(in));
Strings;
while((s=br.readLine())!=null)
result.append(s).append("\n");
}catch(Exceptione){
e.printStackTrace();
}return result.toString(); }
public static String filterMacAddress(String ip, String sourceString,String macSeparator) {
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;
}public static void main(String[] args) {
Stringip="10.81.66.155";
Stringaa=filterMacAddress(ip,callCmd(newString[]{"ping"+ip,"arp"+ip+"-a"}),"-");
System.out.println(aa);
}