The Java implementation gets the user's MAC address

  • 2020-04-01 04:19:52
  • OfStack

Method 1: distinguish the local address from other machines in the LAN



  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 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 as a String
      StringBuilder sb = new StringBuilder();
      for (int i = 0; i < mac.length; i++) {
        if (i != 0) {
          sb.append("-");
        }
        //MAC [I] & 0xFF is used to convert a byte to a positive integer
        String s = Integer.toHexString(mac[i] & 0xFF);
        sb.append(s.length() == 1 ? 0 + s : s);
      }
      //Change all lowercase letters of the string to uppercase to become the regular MAC address and return
      macAddress = sb.toString().trim().toUpperCase();
      return macAddress;
    } else {
      //Gets the MAC address of a 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 look at method two again:


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 {

	
	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, very simple, request-getremoteaddr ();
	//Since the VIew layer of the system is implemented using JSF, there is no way to get a similar request directly on the page, so a cast 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
	//The command to call window is implemented in the background Bean to get the MAC address via IP. Here's how:

	//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;
	}
}

Third, be more concise


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 need to enlarge the recruit, friends look carefully oh

The first thing to say is: this method can support the MAC address of the external network machine.  

Previously, I got a LAN with only access. You can't access it with a firewall, but don't worry about that.
Tested baidu's IP, has been able to get MAC address

Java gets MAC address via IP - seal IP seal MAC address


import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.regex.Matcher;
import java.util.regex.Pattern;



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; 
   }
   
    
   public static String callCmd(String[] cmd,String[] another) { 
     String result = ""; 
     String line = ""; 
     try { 
       Runtime rt = Runtime.getRuntime(); 
       Process proc = rt.exec(cmd); 
       proc.waitFor(); //Having executed the first command, we are ready to execute the second
       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; 
   }
   
   
   
    
   public static String filterMacAddress(final String ip, final String sourceString,final 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; //If there are multiple ips, only the Mac corresponding to this IP is matched.
       } 
     }
  
     return result; 
   }
   
   
   
    
   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; 
   } 

    
   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; 
   } 
   
   
   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"));
   }
  
}


Related articles: