`

Java_How To Get MAC Address

    博客分类:
  • Java
 
阅读更多

from: http://www.mkyong.com/java/how-to-get-mac-address-in-java/

 

Since JDK 1.6, Java developers are able to access network card detail via NetworkInterface class. In this example, we show you how to get the localhost MAC address in Java.

App.java – Get MAC Address via NetworkInterface.getByInetAddress()
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
 
public class App{
 
   public static void main(String[] args){
 
	InetAddress ip;
	try {
 
		ip = InetAddress.getLocalHost();
		System.out.println("Current IP address : " + ip.getHostAddress());
 
		NetworkInterface network = NetworkInterface.getByInetAddress(ip);
 
		byte[] mac = network.getHardwareAddress();
 
		System.out.print("Current MAC address : ");
 
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < mac.length; i++) {
			sb.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : ""));		
		}
		System.out.println(sb.toString());
 
	} catch (UnknownHostException e) {
 
		e.printStackTrace();
 
	} catch (SocketException e){
 
		e.printStackTrace();
 
	}
 
   }
 
}

Output

Current IP address : 192.168.1.22
Current MAC address : 00-26-B9-9B-61-BF
Note
This NetworkInterfaceNetworkInterface.getHardwareAddress() method is only allowed to access localhost MAC address, not remote host MAC address.

Old day...

Before JDK1.6 is released, many are using the command and pattern to get the MAC address in Windows, minor code changes will enable it to get the MAC address in *nux as well.

App.java - Get MAC Address via command & pattern
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
 
public class App{
 
   public static void main(String[] args) throws IOException{
 
       String command = "ipconfig /all";
       Process p = Runtime.getRuntime().exec(command);
 
       BufferedReader inn = new BufferedReader(new InputStreamReader(p.getInputStream()));
       Pattern pattern = Pattern.compile(".*Physical Addres.*: (.*)");
 
       while (true) {
            String line = inn.readLine();
 
	    if (line == null)
	        break;
 
	    Matcher mm = pattern.matcher(line);
	    if (mm.matches()) {
	        System.out.println(mm.group(1));
	    }
	}	    
   }
}

Output

02-00-4E-43-50-49
90-4C-E5-44-B9-8F
00-26-B9-9B-61-BF
00-00-00-00-00-00-00-E0
00-00-00-00-00-00-00-E0
00-00-00-00-00-00-00-E0
00-00-00-00-00-00-00-E0
00-00-00-00-00-00-00-E0

This obsolete method is not really efficient, because it does not display which MAC address is using now, what it did is just print out all the available MAC address currently attached. However, it's nice to share here.

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics