Skip to content

Instantly share code, notes, and snippets.

@timendum
Created July 27, 2011 10:06
Show Gist options
  • Save timendum/1109057 to your computer and use it in GitHub Desktop.
Save timendum/1109057 to your computer and use it in GitHub Desktop.
Get MAC Address in Java
public static void main(String[] args) throws SocketException {
Enumeration<NetworkInterface> networks = NetworkInterface.getNetworkInterfaces();
NetworkInterface inter;
while (networks.hasMoreElements()) {
inter = networks.nextElement();
byte[] mac = inter.getHardwareAddress();
if (mac != null) {
for (int i = 0; i < mac.length; i++) {
System.out.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : "");
}
System.out.println("");
}
}
}
@catapulveda
Copy link

Excelente!

@jogHar
Copy link

jogHar commented Nov 6, 2019

How this code return more than one addresses?

@timendum
Copy link
Author

timendum commented Nov 6, 2019

@jogHar

How this code return more than one address?

You can have more than one network interfaces, LAN and WiFi for example.

@jogHar
Copy link

jogHar commented Nov 6, 2019

@timendum

How this code return more than one address?

You can have more than one network interfaces, LAN and WiFi for example.

Ok, Thanks for reply.

@waleed-anjum
Copy link

it does not return me the mac address which has not assinged any ip address, is there a way to get all mac addresses.

@waleed-anjum
Copy link

for example my machine shows this information when i run ifconfig -a command
ifconfig -a
eth0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500
inet 20.200.21.112 netmask 255.255.255.0 broadcast 20.200.21.255
inet6 fe80::215:5dff:fe3b:f00f prefixlen 64 scopeid 0x20
ether 00:15:5d:3b:f0:0f txqueuelen 1000 (Ethernet)
RX packets 8370578 bytes 3535158575 (3.5 GB)
RX errors 0 dropped 12221 overruns 0 frame 0
TX packets 4350607 bytes 2239294272 (2.2 GB)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0

eth1: flags=4098<BROADCAST,MULTICAST> mtu 1500
ether 00:15:5d:3b:f0:10 txqueuelen 1000 (Ethernet)
RX packets 0 bytes 0 (0.0 B)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 0 bytes 0 (0.0 B)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0

lo: flags=73<UP,LOOPBACK,RUNNING> mtu 65536
inet 127.0.0.1 netmask 255.0.0.0
inet6 ::1 prefixlen 128 scopeid 0x10
loop txqueuelen 1000 (Local Loopback)
RX packets 156676082 bytes 9238057998 (9.2 GB)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 156676082 bytes 9238057998 (9.2 GB)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0

but running this java code mentioned above i just get a single mac address instead of both which is 00155D3BF00F

@Urunov
Copy link

Urunov commented Aug 23, 2022

It is working with me.
3 categories are included :
VPN
WSDL
Ethernet

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment