Merge pull request #9576 from developerDiv/macaddress

BAEL-4155 - MAC Address on Local Machine
This commit is contained in:
rpvilao 2020-06-29 10:53:48 +02:00 committed by GitHub
commit 885c9f456a
2 changed files with 44 additions and 0 deletions

View File

@ -0,0 +1,23 @@
package com.baeldung.macaddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
public class GetAllMacAddressesDemo {
public static void main(String[] args) throws SocketException {
Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
while (networkInterfaces.hasMoreElements()) {
NetworkInterface ni = networkInterfaces.nextElement();
byte[] hardwareAddress = ni.getHardwareAddress();
if (hardwareAddress != null) {
String[] hexadecimalFormat = new String[hardwareAddress.length];
for (int i = 0; i < hardwareAddress.length; i++) {
hexadecimalFormat[i] = String.format("%02X", hardwareAddress[i]);
}
System.out.println(String.join("-", hexadecimalFormat));
}
}
}
}

View File

@ -0,0 +1,21 @@
package com.baeldung.macaddress;
import org.junit.Test;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import static org.junit.Assert.assertEquals;
public class MacAddressUnitTest {
@Test
public void givenNetworkInterface_whenUsingLocalHost_thenGetMacAddress() throws UnknownHostException, SocketException {
InetAddress localHost = InetAddress.getLocalHost();
NetworkInterface ni = NetworkInterface.getByInetAddress(localHost);
byte[] macAddress = ni.getHardwareAddress();
assertEquals(6, macAddress.length);
}
}