Java獲取訪問服務端的客戶端IP和MAC地址
阿新 • • 發佈:2019-02-02
/** * 得到訪問者的IP地址 * @return ip * @throws Exception */ public String getIp() throws Exception{ String ip = request.getHeader("X-Forwarded-For"); if(ip!=null){ if(!ip.isEmpty()&&!"unKnown".equalsIgnoreCase(ip)){ int index = ip.indexOf(","); if (index != -1){ return ip.substring(0,index); }else{ return ip; } } } ip = ServletActionContext.getRequest().getHeader("X-Real-IP"); if(ip!=null){ if (!ip.isEmpty()&&!"unKnown".equalsIgnoreCase(ip)){ return ip; } } return request.getRemoteAddr(); } /** * 通過訪問的Ip地址得到mac地址 * @param ip * @return mac */ public String getMacByIp(String ip){ String macAddress = ""; try { java.lang.Process process = Runtime.getRuntime().exec("nbtstat -A "+ip); InputStreamReader ir = new InputStreamReader(process.getInputStream()); LineNumberReader input = new LineNumberReader(ir); String str = ""; while ((str=input.readLine())!=null){ str = str.toUpperCase(); if(str.indexOf("MAC ADDRESS")>1){ int start = str.indexOf("="); macAddress = str.substring(start+1,str.length()).trim(); break; } } } catch (IOException e) { e.printStackTrace(); } return macAddress; }