如何获得客户端的IP及MAC地址
?
?
1、获得真实的IP地址
public static String getIpAddr(HttpServletRequest request) {
??String ip = 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();
??}
??return ip;
?}
?
2、下面两个方法,是获得MAC地址。
public static String callCmd(String[] cmd) {??
??????? StringBuilder result = new StringBuilder("");??
??????? String line = "";??
??????? try {
??????? ?Process proc=null;
??????? ?for(String tmp:cmd){?????????
??????????proc = Runtime.getRuntime().exec(tmp);???
????????? proc.waitFor();
?????????}
??????? ?BufferedInputStream in = new BufferedInputStream(proc.getInputStream());
??????????? BufferedReader br = new BufferedReader(new InputStreamReader(in));
??????????? String s;
??????????? while ((s = br.readLine()) != null)
??????????? ?result.append(s).append("\n");
??????? } catch (Exception e) {
??????? ?e.printStackTrace();
??????? }
??????? return result.toString();??
??? }??
public static String filterMacAddress(String ip, String sourceString,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;??
???? }??
?
?public static void main(String[] args) {
? String ip ="10.81.66.155";
??String aa= filterMacAddress(ip,callCmd(new String[]{"ping "+ip,"arp?"+ip+" -a"}),"-");
??System.out.println(aa);
?}