Move to java-core-networking-2

This commit is contained in:
developerDiv 2020-06-24 22:07:48 +01:00
parent a3a452c108
commit bb2060ee78
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.assertNotNull;
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();
assertNotNull(macAddress);
}
}