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()
package com.mkyong;
 
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
package com.mkyong;
 
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.

Tags :

About the Author

mkyong
Founder of Mkyong.com and HostingCompass.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.

Comments

  • Azhar

    Thanks Mr.mkyong

  • Triguna

    This is a nice article. However I have a question, how do we differentiate between various types of cards like Ethernet, Wireless etc., even though I could get the mac address, if I cant differentiate the mac address of what? will it be actually useful?
    Is there a way we can do that today?

  • http://tokobagus.com Dino Noid

    This code doesn’t work on Ubuntu 12.4 . The network returned from

    NetworkInterface.getByInetAddress(ip)

    will be null.

    • Prasanna

      Seconded !!

      • sai pitta

        Use this….
        String mac = null;
        InetAddress ip = InetAddress.getLocalHost();

        Enumeration e = NetworkInterface.getNetworkInterfaces();

        while(e.hasMoreElements()) {

        NetworkInterface n = (NetworkInterface) e.nextElement();
        Enumeration ee = n.getInetAddresses();
        while(ee.hasMoreElements()) {
        InetAddress i = (InetAddress) ee.nextElement();
        if(!i.isLoopbackAddress() && !i.isLinkLocalAddress() && i.isSiteLocalAddress()) {
        ip = i;
        }
        }
        }

        NetworkInterface network = NetworkInterface.getByInetAddress(ip);
        byte[] mac_byte = network.getHardwareAddress();

        StringBuilder sb = new StringBuilder();
        for(int i = 0; i < mac_byte.length; i++) {
        sb.append(String.format("%02X%s", mac_byte[i], (i < mac_byte.length -1) ? "-" : ""));
        }
        mac = sb.toString();
        System.out.println(mac);

  • Touhid

    Dude, I love you blog :D thanks for all your effort !

  • Domendron

    Encontrei um outro muito mais incrementada, confiram:

    import java.io.IOException;
    import java.net.*;

    /**
    *
    * @author Guilherme Abreu
    * @mail [email protected]
    * testeMac.java
    *
    */

    public class testeMac {

    public static void main(String[] args) throws IOException {
    new testeMac().getMacAddress();
    }

    private void getMacAddress() throws SocketException, UnknownHostException {
    InetAddress localHost = InetAddress.getLocalHost();
    NetworkInterface netInter = NetworkInterface.getByInetAddress( localHost );
    byte[] macAddressBytes = netInter.getHardwareAddress();

    for (int i = 0; i <= 5; i++) {

    System.out.print((Integer.toHexString(macAddressBytes[i] & 0xff)).toUpperCase());
    if(i<5){System.out.print("-");}

    }

    }

    }

    • Hardik Patel
       
      import java.io.IOException;
      import java.net.*;
       
      /**
      *
      * @author Guilherme Abreu
      * @mail [email protected]
      * testeMac.java
      *
      */
       
      public class testeMac {
       
      public static void main(String[] args) throws IOException {
      new testeMac().getMacAddress();
      }
       
      private void getMacAddress() throws SocketException, UnknownHostException {
      InetAddress localHost = InetAddress.getLocalHost();
      System.out.print(&quot;local ip&quot; +localHost);
       
      NetworkInterface netInter = NetworkInterface.getByInetAddress( localHost );
      byte[] macAddressBytes = netInter.getHardwareAddress();
      System.out.println(&quot;local mac :&quot;);
      for (int i = 0; i &lt;= 5; i++) {
       
      System.out.print((Integer.toHexString(macAddressBytes[i] &amp; 0xff)).toUpperCase());
      if(i&lt;5){System.out.print(&quot;-&quot;);}
       
      }
       
       
      InetAddress remoteHost = InetAddress.getByName(&quot;www.google.co.in&quot;);
       
      System.out.print(&quot;Remot ip&quot; +remoteHost);
      NetworkInterface remotenetInter = NetworkInterface.getByInetAddress( remoteHost );
      System.out.println(&quot;remote mac :&quot;);
       
      byte[] macremoteAddressBytes = remotenetInter.getHardwareAddress();
       
      for (int i = 0; i &lt;= 5; i++) {
       
      System.out.print((Integer.toHexString(macremoteAddressBytes[i] &amp; 0xff)).toUpperCase());
      if(i&lt;5){System.out.print(&quot;-&quot;);}
       
      }
       
      }
       
      }
    • Hardik Patel

      hi….thanks for reply but this code does not provide enough information what i want is…..i have IP address of “www.google.com” by using command InetAddress.getByName but i want MAC address of this server. i posted modified code try to run this code it give null pointer exception instead of MAC address of that server……

  • Hardik Patel
     is it possible to get MAC address of remote machine using ip address of that remote machine? how?
  • Hardik Patel

    Is it possible to get mac address of remote machine using ip address of that remote machine?
    how?

  • abas

    Hello my friend
    please how can i use this in oracle form builder 10g to get the mac address of the server.
    thanks for help me

  • A.ACHARYA

    By using above code i can not access the mac address of my client machine.
    nic.getHardwareAddress() always return null.
    plz give another suggestion.

  • Jacorb Effect

    I think you need to be able to skip the loop-back adapter

            private String getMacAddress() {
                try {
                    Enumeration&lt;NetworkInterface&gt; en = NetworkInterface.getNetworkInterfaces();
                    while (en.hasMoreElements()) {
                        NetworkInterface nic = en.nextElement();
                        if (nic.isLoopback()) {
                            continue;
                        }
                        byte[] mac = nic.getHardwareAddress();
                        StringBuilder sb = new StringBuilder();
                        for (int i = 0; i &lt; mac.length; i++) {
                            sb.append(String.format(&quot;%02X%s&quot;, mac[i], (i &lt; mac.length - 1) ? &quot;-&quot; : &quot;&quot;));
                        }
                        //System.out.println(sb.toString());
                        return sb.toString();
                    }
                }
                catch (SocketException ex) {
                    return &quot;Unknown MAC Address&quot;;
                }            
                return &quot;Unknown MAC Address&quot;;
            }
  • Jay

    I manually changed my MAC Address then loaded this page. To my surprise your code pulled my ACTUAL MAC address not the changed version. How is this possible? I’m a big advocate of privacy on the internet particularly from juggernauts like Google and Facebook. I am curious if there any way to actually change the MAC address that Java pulls?

    • Rob

      The code has direct access to the hardware and can thus read the address regardless of the changes another program makes. The MAC address is hard coded to a ROM chip and cannot be changed. As long as the code is not run remotely it will pull the actual address.

      • Alexander

        As I pointed out some time ago, this code will grab MAC address of a Cisco VPN virtual adapter(which is a peace of software btw.). Thus, in a strict sense your statement “read the address regardless of the changes another program makes” applied to this particular peace of code is not correct. The only point I am trying to make here is that one should not blindly rely on this MAC address detection technique for sensitive things like identifying machines for software licensing purposes – it can be easily forged.

    • Alexander

      MAC address is the least of your worries regarding privacy in the internet. Sender and receiver MAC addresses are only used inside of your “last hop” Ehternet LAN in the most typical scenario. Packets that you receive and send are identified by IP addresses (which will also often be not your direct LAN IP, but an IP of your router + NAT). Furthermore, MAC addresses will be discarded as soon as your packet leaves Ethernet transport network and other Layer 2 technology is used as they only make sense in this limited domain. It is the task of your router to find out and inject correct MAC of you machine using ARP (address resolution protocol). If you are paranoid about privacy and want to fight some windmills, IPv6 is your target.

      PS: if you want to understand how networks work, I would recommend getting acquainted with this: books.google.de/books?isbn=0130661023

  • Darlington

    Please how do two computers (client and server) communicate using MAC address. I want the client to be able to send a message to the server using MAC address. Thanks.

  • ArlexWong

    just i read above your coding,is very convenience and good try of your coding:)
    hmm.. i have a problem in my assignment, i donno how to using MAC address to send a msg through in client and server, using IP address is success now , only MAC =.=
    can you giv some tips for me ? thanks =D

  • Joe Pisquali

    How do I get all the MAC Addresses if my computer has more than one NIC?

  • Alexander

    WARNING: The first method will always return Cisco┬┤s MAC, when connected to VPN via Cisco Client.

  • Pingback: Getting Mac Address()

  • sudheer

    Hi,

    In the above example i got error .i.e
    byte[] mac = network.getHardwareAddress();

    No getHardwareAddress()method found in NetworkInterface class.Is it correct or my program is incorrect?

    Thanks,

  • http://www.jdbctutorial.net WebDev

    Hi Yong.

    Is their any way to get client MAC address using Java or JavaScript?

    • http://www.mkyong.com mkyong

      This example is implemented in Java, i don’t think JavaScript is able to access the client network card detail.

      • http://www.jdbctutorial.net WebDev

        Thanks.

        Can we use Applet to know Client MAC Address?

        • http://www.mkyong.com mkyong

          Never try before, but Applet should be able to get client’s MAC address IF your Applet is signed and trusted by client.

          • Pratik

            Can u show how i can use applet to fetch mac address. i am all confused and could not work out well on it.

  • http://yogi.rampuria.org Yogi

    Obselete Method also had many flaws
    1) Different code for Linux/Unix/Solaris platform
    2) Also it was easy to be bluffed. Suppose you app uses Mac address for generating some unique code for licensing purposes. One has to just have one license based on one mac address and then just write a small batch file ipconfig.bat (in windows) and put it in the apps working directory. Content could be just simple echo statements that produce same output as the licensed host and BANG! Believe it or not I have seen it in producation grade code ;lolz

    • http://www.mkyong.com mkyong

      hi yogi,

      Thanks for your input and invaluable experience on this :)