Method 1: Distinguish the local machine address from other machines in the LAN
/** * Get the mac address based on the IP address * @param ipAddress 127.0.0.1 * @return * @throws SocketException * @throws UnknownHostException */ public static String getLocalMac(String ipAddress) throws SocketException, UnknownHostException { // TODO Auto-generated method stub String str = ""; String macAddress = ""; final String LOOPBACK_ADDRESS = "127.0.0.1"; // If it is 127.0.0.1, get the local MAC address. if (LOOPBACK_ADDRESS.equals(ipAddress)) { InetAddress inetAddress = InetAddress.getLocalHost(); // It seems that this method requires JDK1.6. byte[] mac = NetworkInterface.getByInetAddress(inetAddress) .getHardwareAddress(); // The following code assembles the mac address into String StringBuilder sb = new StringBuilder(); for (int i = 0; i < mac.length; i++) { if (i != 0) { sb.append("-"); } // mac[i] & 0xFF It is to convert byte into a positive integer String s = Integer.toHexString(mac[i] & 0xFF); sb.append(s.length() == 1 ? 0 + s : s); } // Convert all strings Change the lowercase letters to uppercase to become the regular mac address and return macAddress = sb.toString().trim().toUpperCase(); return macAddress; } else { // Get the MAC address of the non-local IP try { System.out.println(ipAddress); Process p = Runtime.getRuntime() .exec("nbtstat -A " + ipAddress); System.out.println("= ==process=="+p); InputStreamReader ir = new InputStreamReader(p.getInputStream()); BufferedReader br = new BufferedReader(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 (IOException ex) { } return macAddress; } }
Let’s take a look at method two:
package com.alpha.test;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.io.LineNumberReader;public class GetMac {/** * java gets the MAC address of the client network card * * @param args */public static void main(String[] args) {GetMac get = new GetMac();System.out.println("1="+get.getMAC());System.out.println("2="+get.getMAC("127.0.0.1"));}// 1 .Get the client IP address (this must be passed from the client to the background): // Under the jsp page, it is very simple, request.getRemoteAddr();// Because the VIew layer of the system is implemented with JSF, similar requests cannot be obtained directly on the page, so a forced conversion is made in the bean // public String getMyIP() {// try {// FacesContext fc = FacesContext.getCurrentInstance ();// HttpServletRequest request = (HttpServletRequest) fc// .getExternalContext().getRequest();// return request.getRemoteAddr();// } catch (Exception e) {// e.printStackTrace();// }// return "";// }// 2. Get the client mac address // Call the window command , in the background Bean, obtain the mac address through ip. The method is as follows: // Running speed [fast] public String getMAC() {String mac = null; try {Process pro = Runtime.getRuntime().exec("cmd.exe /c ipconfig/all");InputStream is = pro .getInputStream();BufferedReader br = new BufferedReader(new InputStreamReader(is));String message = br.readLine();int index = -1;while (message != null) {if ((index = message.indexOf("Physical Address")) > 0) {mac = message.substring(index + 36).trim();break;}message = br.readLine();}System.out.println(mac);br.close();pro.destroy();} catch (IOException e) {System.out.println("Can't get mac address!");return null;}return mac;}//Running speed [slow] public String getMAC(String ip) {String str = null;String macAddress = null ;try {Process p = Runtime.getRuntime().exec("nbtstat -A " + ip);InputStreamReader ir = new InputStreamReader(p.getInputStream());LineNumberReader input = new LineNumberReader(ir);for (; true;) {str = input.readLine();if (str != null) {if (str.indexOf("MAC Address ") > 1) {macAddress = str.substring(str.indexOf("MAC Address") + 14);break;}}}} catch (IOException e) {e.printStackTrace(System.out);return null;}return macAddress;}}
Method three, more streamlined
import java.io.IOException;import java.io.InputStreamReader;import java.io.LineNumberReader;public class MACAddress { String ip; String mac; public MACAddress (String ip){ this.ip = ip; } public MACAddress (){ this.ip = "0.0.0.0"; } public String getMac(){ try { Process p = Runtime.getRuntime().exec("arp -n"); InputStreamReader ir = new InputStreamReader(p.getInputStream()); LineNumberReader input = new LineNumberReader(ir); p.waitFor(); boolean flag = true; String ipStr = "(" + this.ip + ")"; while(flag) { String str = input.readLine(); if (str != null) { if (str.indexOf(ipStr) > 1) { int temp = str.indexOf("at"); this.mac = str.substring( temp + 3, temp + 20); break; } } else flag = false; } } catch (IOException | InterruptedException e) { e.printStackTrace(System.out); } return this.mac; } public void setIp(String ip){ this.ip = ip; }}
Finally, we have to enlarge the move, friends, watch carefully.
The first thing to say is: This method can support obtaining the mac address of the external network machine.
I used to have one that could only access the LAN. You can't access it if you have a firewall, but you don't have to worry about this.
I tested Baidu’s IP and can get the mac address.
java gets mac address through ip - block ip block mac address
import java.io.BufferedReader;import java.io.InputStreamReader;import java.util.regex.Matcher;import java.util.regex.Pattern;/*** Get MAC address* @author* 2011-12*/public class GetMacAddress { public static String callCmd(String[] cmd) { String result = ""; String line = ""; try { Process proc = Runtime.getRuntime().exec(cmd); InputStreamReader is = new InputStreamReader(proc.getInputStream()); BufferedReader br = new BufferedReader (is); while ((line = br.readLine ()) != null) { result += line; } } catch(Exception e) { e.printStackTrace(); } return result; } /** * * @param cmd first command* @param another second command* @return execution result of the second command*/ public static String callCmd(String[] cmd,String[] another) { String result = ""; String line = ""; try { Runtime rt = Runtime.getRuntime(); Process proc = rt.exec(cmd); proc.waitFor(); //The first command has been executed and the second command has been executed proc = rt.exec(another); InputStreamReader is = new InputStreamReader(proc.getInputStream()); BufferedReader br = new BufferedReader (is); while ((line = br.readLine ()) != null) { result += line; } } catch(Exception e) { e.printStackTrace(); } return result; } /** * * @param ip Target ip, usually within the LAN* @param sourceString The result string of command processing* @param macSeparator mac separator symbol* @return mac address, represented by the separator symbol above*/ public static String filterMacAddress(final String ip, final String sourceString ,final String macSeparator) { String result = ""; String regExp = "((([0-9,AF,af]{1,2}" + macSeparator + "){1,5})[0-9,AF,af]{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; //If there are multiple IPs, only the Mac corresponding to this IP is matched. } } return result; } /** * * @param ip target ip * @return Mac Address * */ public static String getMacInWindows(final String ip){ String result = ""; String[] cmd = { "cmd", "/c", "ping " + ip }; String[] another = { "cmd", "/c", "arp -a" }; String cmdResult = callCmd(cmd,another); result = filterMacAddress(ip,cmdResult,"-"); return result; } /** * @param ip target ip * @return Mac Address * */ public static String getMacInLinux(final String ip){ String result = ""; String[] cmd = { "/bin/sh", "-c", "ping " + ip + " -c 2 && arp -a" }; String cmdResult = callCmd(cmd); result = filterMacAddress(ip,cmdResult,":"); return result; } /** * Get the MAC address* @return Return the MAC address*/ public static String getMacAddress(String ip){ String macAddress = ""; macAddress = getMacInWindows(ip).trim(); if(macAddress==null||"".equals(macAddress)){ macAddress = getMacInLinux(ip).trim(); } return macAddress; } //Do a test public static void main(String[] args) { System .out.println(getMacAddress("220.181.111.148")); } }