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.
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.
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.?
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
I think you need to be able to skip the loop-back adapter
Thanks for the code!
Works. Thanks 🙂
how to get mac address of bluetooth devices that paired with the laptop?
how can i get the IP and MAC address of the different access point detected by the wireless card
Please advise can I get mac address of remote client who is accessing my application. Search a lot but did not find . please advise..
Ho to get mac address for LAN/Ethernate?
I need to find the mac address using IBM Lotus notes lotus script, how can i use your code to get mac address.
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
*nux -> *nix 😉
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?
Can you help me out How to validate my application by MAC Address !
Thanks Mr.mkyong
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?
hey …please reply me if got something about the same….
This code doesn’t work on Ubuntu 12.4 . The network returned from
NetworkInterface.getByInetAddress(ip)
will be null.
Seconded !!
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);
Dude, I love you blog 😀 thanks for all your effort !
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("-");}
}
}
}
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……
Is it possible to get mac address of remote machine using ip address of that remote machine?
how?
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.
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
By using above code i can not access the mac address of my client machine.
nic.getHardwareAddress() always return null.
plz give another suggestion.
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?
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
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.
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.
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.
I think there is only one viable answer to your question:
http://www.amazon.de/Computer-Networks-4th-Edition-ebook/dp/B00371V7RO/ref=sr_1_1?s=digital-text&ie=UTF8&qid=1353335401&sr=1-1
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
How do I get all the MAC Addresses if my computer has more than one NIC?
WARNING: The first method will always return Cisco´s MAC, when connected to VPN via Cisco Client.
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,
Hi Yong.
Is their any way to get client MAC address using Java or JavaScript?
This example is implemented in Java, i don’t think JavaScript is able to access the client network card detail.
Thanks.
Can we use Applet to know Client MAC Address?
Never try before, but Applet should be able to get client’s MAC address IF your Applet is signed and trusted by client.
Can u show how i can use applet to fetch mac address. i am all confused and could not work out well on it.