java gets the user's MAC address in detail for multiple method instances

  • 2020-07-21 07:45:04
  • OfStack

java realizes the MAC address method of obtaining users:

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


/**
  *  According to the IP The address for mac 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 is a mac The address is assembled String
   StringBuilder sb = new StringBuilder();
   for (int i = 0; i < mac.length; i++) {
    if (i != 0) {
     sb.append("-");
    }
    // mac[i] & 0xFF  Is for the sake of the 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 make it normal mac Address and return 
   macAddress = sb.toString().trim().toUpperCase();
   return macAddress;
  } else {
   //  Get non-local IP the MAC address 
   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 2 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 { 
  /**
   * java Get the client network card MAC address 
   * 
   * @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 client ip address (  This must be passed from the client to the background ) : 
  // jsp Under the page, very simple, request.getRemoteAddr() ;
  //  Because of systematic VIew Layer is used JSF To achieve, so the page can not directly get similar request In the bean I made a cast  
  // 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 client mac address 
  //  call window Command, in the background Bean In the implementation   through ip In order to get mac Address. The methods are 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 3, more concise 1:


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

The first thing to note is that this method supports mac address fetching for an extranet machine.

Before getting 1 can only access the LAN. You can't access it with a firewall, but don't worry about that.

Baidu ip has been tested and the mac address can be obtained

java gets the mac address from ip - seal ip seal mac address


import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.regex.Matcher;
import java.util.regex.Pattern; 
/**
*  To obtain 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  The first 1 A command  
  * @param another  The first 2 A command  
  * @return  The first 2 The result of the execution of three commands  
  */
  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 control has been executed 1 One command, ready to execute number one 2 A command  
    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  The target ip,1 Generally in the LAN  
  * @param sourceString  The result string processed by the command  
  * @param macSeparator mac separator  
  * @return mac Address, indicated by the separator above  
  */
  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 you have more than one IP, Matches only the IP The corresponding Mac. 
    } 
   }  
   return result; 
  }   
  /** 
  * 
  * @param ip  The 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  The 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; 
  }  
  /**
  *  To obtain MAC address  
  * @return  return 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"));
  }
 }

I hope you found this article helpful


Related articles: