?Java?,?????????????MAC??:
- ??
NetworkInterface
?:
import java.net.NetworkInterface; import java.net.SocketException; import java.util.Enumeration; public class MacAddressUtil { public static String getMacAddress() { try { EnumerationnetworkInterfaces = NetworkInterface.getNetworkInterfaces(); while (networkInterfaces.hasMoreElements()) { NetworkInterface networkInterface = networkInterfaces.nextElement(); byte[] mac = networkInterface.getHardwareAddress(); if (mac != null) { StringBuilder stringBuilder = new StringBuilder(); for (byte b : mac) { stringBuilder.append(String.format("X:", b)); } if (stringBuilder.length() > 0) { stringBuilder.deleteCharAt(stringBuilder.length() - 1); } return stringBuilder.toString(); } } } catch (SocketException e) { e.printStackTrace(); } return null; } public static void main(String[] args) { String macAddress = getMacAddress(); System.out.println(macAddress); } }
- ??
InetAddress
????????IP??,????Process
???arp -a
??,?????????MAC??:
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.InetAddress; import java.net.UnknownHostException; public class MacAddressUtil { public static String getMacAddress() { String ipAddress = null; try { InetAddress inetAddress = InetAddress.getLocalHost(); ipAddress = inetAddress.getHostAddress(); } catch (UnknownHostException e) { e.printStackTrace(); } if (ipAddress != null) { try { Process process = Runtime.getRuntime().exec("arp -a"); BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream())); String line; while ((line = reader.readLine()) != null) { if (line.contains(ipAddress)) { int index = line.indexOf("at") + 3; return line.substring(index); } } } catch (IOException e) { e.printStackTrace(); } } return null; } public static void main(String[] args) { String macAddress = getMacAddress(); System.out.println(macAddress); } }
???,??MAC?????????????????