Main Tutorials

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.

About Author

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

Subscribe
Notify of
49 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Aijaz Mustufa
9 years ago

Is it possible to get mac address of offline laptop machine, i have tried the same code(Get MAC Address via NetworkInterface.getByInetAddress()) and getting blank mac address while offline?

Can you help me out.?

pranish shrestha
9 years ago

The problem with the first code is that it takes mac address of virtual machine if it is installed in your system. You will have to disable the virtual network adapter and then only it gives the mac address of the current network card

Jacorb Effect
11 years ago

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

        private String getMacAddress() {
            try {
                Enumeration<NetworkInterface> 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 < mac.length; i++) {
                        sb.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : ""));
                    }
                    //System.out.println(sb.toString());
                    return sb.toString();
                }
            }
            catch (SocketException ex) {
                return "Unknown MAC Address";
            }            
            return "Unknown MAC Address";
        }
Zyretc
2 years ago

Thanks for the code!

Eliajh
6 years ago

Works. Thanks 🙂

jimmy
8 years ago

how to get mac address of bluetooth devices that paired with the laptop?

Aisha M
8 years ago

how can i get the IP and MAC address of the different access point detected by the wireless card

Pawan Soni
8 years ago

Please advise can I get mac address of remote client who is accessing my application. Search a lot but did not find . please advise..

Amit
8 years ago

Ho to get mac address for LAN/Ethernate?

Haider Shahzad
8 years ago

I need to find the mac address using IBM Lotus notes lotus script, how can i use your code to get mac address.

Arun Gaur
8 years ago

can any one help me for givingme java full source code for finding the mac address of conecting computer in a virtual network.
i wanna just if ppossible so fast plz

logoff
9 years ago

*nux -> *nix 😉

Vatsal desai
9 years ago

This is a nice article.Executing the first App that is the one using

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());

Is not giving MAC address on Ubuntu 14.04.Is there any change needed to run it on Ubuntu?

Haroon Mind
9 years ago

Can you help me out How to validate my application by MAC Address !

Azhar
10 years ago

Thanks Mr.mkyong

Triguna
10 years ago

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?

Primus
10 years ago
Reply to  Triguna

hey …please reply me if got something about the same….

Dino Noid
10 years ago

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

NetworkInterface.getByInetAddress(ip)

will be null.

Prasanna
10 years ago
Reply to  Dino Noid

Seconded !!

sai pitta
10 years ago
Reply to  Prasanna

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
10 years ago

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

Domendron
11 years ago

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
11 years ago
Reply to  Domendron

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
11 years ago
Reply to  Domendron

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("local ip" +localHost);

NetworkInterface netInter = NetworkInterface.getByInetAddress( localHost );
byte[] macAddressBytes = netInter.getHardwareAddress();
System.out.println("local mac :");
for (int i = 0; i <= 5; i++) {

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

}


InetAddress remoteHost = InetAddress.getByName("www.google.co.in");

System.out.print("Remot ip" +remoteHost);
NetworkInterface remotenetInter = NetworkInterface.getByInetAddress( remoteHost );
System.out.println("remote mac :");

byte[] macremoteAddressBytes = remotenetInter.getHardwareAddress();

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

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

}

}

}


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

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

Stefano Castagnino
8 years ago
Reply to  Hardik Patel

I known is possible but first you must known the ip address change but usually the mac address does not. So if you got the ip address any machine you must get the mac address in that time.

abas
11 years ago

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
11 years ago

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

Jay
11 years ago

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?

Alexander
11 years ago
Reply to  Jay

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

Rob
11 years ago
Reply to  Jay

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
11 years ago
Reply to  Rob

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.

Darlington
11 years ago

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.

Alexander
11 years ago
Reply to  Darlington
ArlexWong
11 years ago

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
11 years ago

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

Alexander
11 years ago

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

sudheer
12 years ago

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,

WebDev
13 years ago

Hi Yong.

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

WebDev
13 years ago
Reply to  mkyong

Thanks.

Can we use Applet to know Client MAC Address?

Pratik
11 years ago
Reply to  mkyong

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