Find MAC address using Java

Recently i wanted to get the MAC addresses of the computer i was working from within my Java program. I started a small quest and all over there was this tip “this is system dependent so you need to make system calls”. Somewhere around there i found a “but”. Someone posted that in mustang (that is jdk 1.6 or jre 6) tings have changed a little and you can get all this info from a Java class without a system call.

Don’t get me wrong, system calls are not bad but there is a major defect on that approach. When you do a system call there goes the “write once, run everywhere”. I mean you get system dependent. If there is an absolute need to do so and there is no other solution i guess that is ok. But when i stumble upun such problems i always try to find out a way to do it without getting system dependent.

Enough with the fluff. Let’s get down to the point. The main classes you need to concentrate on are and With these two you can do all the dirty job. Now, if you feel adventurus then stop reading and go find your way around after this tip. If you want the solution keep going 😉

  1. try {
  2.     InetAddress []mac = InetAddress.getAllByName(InetAddress.getLocalHost().getHostName());
  3.     /*
  4.      * Get NetworkInterfaces for the current host and then read the
  5.      * hardware addresses.
  6.      */
  7.     for(int i=0; i
  8. < mac.length; i++) {
  9.             System.out.format("%02X%s", mac[i], (i < mac.length1) ? "-" : "");
  10.         }
  11.         System.out.println();
  12.     }
  13. }

Easy huh? This way all you do is list all the network devices on the machine and get the MAC addresses. Make one thing clear though. It’s all the devices. In my machine that meant both real and virtual devices (such as some microsoft bridges and the VMware ones). So if you want to do something with one of them beware which one you choose 😉

4 Responses to “ “Find MAC address using Java”

  1. René says:

    Thanks for this article, it’s just what i was looking for. 😛

  2. scott says:

    Thanks for this article – really good intro and conclusion notes!

    Just a quick note on the code it appears to be missing some code to define variable mac

    Typically NetworkInterface.getHardwareAddress()

    full version of code here
    but not nearly as well explained.

  3. roman@wlan says:

    Does my mac adresse change if I upgrade my computer with some other hardware? For example change the graphic card?

  4. Rukiy says:

    thank you, this is I need.

Leave a Reply