Created
December 2, 2016 14:53
-
-
Save kaminomisosiru/9413b267a0edf9d29cc61d36df03d492 to your computer and use it in GitHub Desktop.
get valid MAC Address
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.net.NetworkInterface; | |
import java.util.Enumeration; | |
public class Main { | |
public static void main(String[] args) throws Exception{ | |
Enumeration<NetworkInterface> nics = NetworkInterface.getNetworkInterfaces(); | |
while (nics.hasMoreElements()) { | |
NetworkInterface ni = nics.nextElement(); | |
if(ni.getHardwareAddress() != null && ni.isUp() && ni.getHardwareAddress().length == 6) { | |
System.out.println("Name : " + ni.getName()); | |
System.out.println("Display name : " + ni.getDisplayName()); | |
System.out.println("isUp : " + ni.isUp()); | |
System.out.println("Hardware address: " + bytesToHexString(ni.getHardwareAddress())); | |
} | |
} | |
} | |
public static String bytesToHexString(byte[] bytes) { | |
StringBuilder sb = new StringBuilder(2 * bytes.length); | |
String s; | |
for (byte b : bytes) { | |
s = Integer.toHexString(b & 0xff); | |
if (s.length() == 1) sb.append('0'); | |
sb.append(Integer.toHexString(b & 0xff)); | |
} | |
return sb.toString(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment