我正在开发一个用于安全投票系统的应用程序。我需要获取特定机器的 MAC 地址以设置为"投票机"。如何获取客户端计算机的 MAC 地址?
//InetAddress address = InetAddress.getLocalHost();
InetAddress address = InetAddress.getByName("192.168.46.53");
/*
* Get NetworkInterface for the current host and then read the
* hardware address.
*/
NetworkInterface ni = NetworkInterface.getByInetAddress(address);
if (ni != null) {
byte[] mac = ni.getHardwareAddress();
if (mac != null) {
/*
* Extract each array of mac address and convert it to hexa with the
* following format 08-00-27-DC-4A-9E.
*/
for (int i = 0; i < mac.length; i++) {
System.out.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : "");
}
} else {
// Address doesn't exist or is not accessible.
}
} else {
// Network Interface for the specified address is not found.
}
以下是我实现的代码,它对我有用。这段代码来自:在jsp java中获取mac地址IP地址。
守则如下:
<%@ page import="java.net.*" %>
<%@ page import="java.util.*" %>
<%@ page import="java.io.*" %>
<%@ page import="java.util.*" %>
<%
InetAddress inetAddress;
StringBuilder sb = new StringBuilder();
String ipAddress="",macAddress="";
int i=0;
try {
inetAddress=InetAddress.getLocalHost();
ipAddress=inetAddress.getHostAddress();
NetworkInterface network=NetworkInterface.getByInetAddress(inetAddress);
byte[] hw=network.getHardwareAddress();
for(i=0; i<hw.length; i++)
sb.append(String.format("%02X%s", hw[i], (i < hw.length - 1) ? "-" :
""));
macAddress=sb.toString();
} catch(Exception e) {
out.print("<br/>"+e.toString());
macAddress="-";
}
out.print("<br/>"+ipAddress);
out.print("<br/>"+macAddress);
%>