Merge pull request #9576 from developerDiv/macaddress
BAEL-4155 - MAC Address on Local Machine
This commit is contained in:
commit
885c9f456a
|
@ -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));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
|
@ -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);
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue