Here's an example that will list the name and MAC for network interfaces found in Java 6:
Enumeration<NetworkInterface> e = NetworkInterface.getNetworkInterfaces();
while (e.hasMoreElements()) {
NetworkInterface ni = e.nextElement();
if (!ni.isUp()) {
continue;
}
byte[] address = ni.getHardwareAddress();
if (address == null || address.length == 0) {
continue;
}
StringBuilder sb = new StringBuilder(2 * address.length);
for (byte b : address) {
sb.append("0123456789ABCDEF".charAt((b & 0xF0) >> 4));
sb.append("0123456789ABCDEF".charAt((b & 0x0F)));
sb.append(":");
}
sb.deleteCharAt(sb.length() - 1);
String mac = sb.toString();
System.out.println(ni.getName() + " " + mac);
}
You could easily get more than one (I get 3 due to VMware network adapters). It is possible to determine the NetworkInterface
for a particular InetAddress
. You can query it for localhost and it works:
InetAddress localhost = InetAddress.getLocalHost();
NetworkInterface ni = NetworkInterface.getByInetAddress(localhost);
However I've discovered that if I'm connecting to a VPN it'll give an empty MAC address. So I'm not entirely sure how to reliably get the MAC you need if you're dealing with systems that could be configured differently. Hope this helps though.
Once you have the right MAC address you can open a URL to send it to your server like this:
new URL("http://server?mac=" + mac).openStream().close();