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 the Author

author image
mkyong
Founder of Mkyong.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

Leave a Reply

avatar
newest oldest most voted
Mohd Tauqeer Ullah
Guest
Mohd Tauqeer Ullah

Can i get the explanation of the code 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());

Eliajh
Guest
Eliajh

Works. Thanks :)

jimmy
Guest
jimmy

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

Aisha M
Guest
Aisha M

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

Pawan Soni
Guest
Pawan Soni

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
Guest
Amit

Ho to get mac address for LAN/Ethernate?

Haider Shahzad
Guest
Haider Shahzad

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
Guest
Arun Gaur

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
Guest
logoff

*nux -> *nix ;)

pranish shrestha
Guest
pranish shrestha

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

Vatsal desai
Guest
Vatsal desai

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?

Aijaz Mustufa
Guest
Aijaz Mustufa

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.?

Haroon Mind
Guest
Haroon Mind

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

Azhar
Guest
Azhar

Thanks Mr.mkyong

Triguna
Guest
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?

Primus
Guest
Primus

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

Dino Noid
Guest
Dino Noid

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

NetworkInterface.getByInetAddress(ip)

will be null.

Prasanna
Guest
Prasanna

Seconded !!

sai pitta
Guest
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
Guest
Touhid

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

Domendron
Guest
Domendron
Encontrei um outro muito mais incrementada, confiram: import java.io.IOException; import java.net.*; /** * * @author Guilherme Abreu * @mail guissj@ig.com.br * 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
Guest
Hardik Patel

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

/**
*
* @author Guilherme Abreu
* @mail guissj@ig.com.br
* 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
Guest
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
Guest
Hardik Patel
 is it possible to get MAC address of remote machine using ip address of that remote machine? how? 
Hardik Patel
Guest
Hardik Patel

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

Stefano Castagnino
Guest
Stefano Castagnino

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
Guest
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
Guest
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
Guest
Jacorb Effect
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"; }
Jay
Guest
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
Guest
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
Guest
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
Guest
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… Read more »
Darlington
Guest
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.

Alexander
Guest
Alexander
ArlexWong
Guest
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
Guest
Joe Pisquali

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

Alexander
Guest
Alexander

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

trackback
Getting Mac Address

[…] banning, & Ip Logging. I'm using it for IP Logging and eventually mac ban. Credits: Me & Java In Player.java: Below: […]

sudheer
Guest
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,