Skip to content

Instantly share code, notes, and snippets.

@narita1980
Created July 6, 2012 02:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save narita1980/3057659 to your computer and use it in GitHub Desktop.
Save narita1980/3057659 to your computer and use it in GitHub Desktop.
NetworkInterfaceを使いMACアドレスを取得する(要JDK1.6以上)
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class SampleGetMacAddress {
public static void main(String args[]) {
try {
Map<String, String> macAdd = getMacAddress();
for(String key : macAdd.keySet()) {
System.out.println(key + " : " + macAdd.get(key));
}
} catch (SocketException e) {
e.printStackTrace();
}
}
public static Map<String,String> getMacAddress() throws SocketException {
String nicaddr = "";
Map map = new HashMap();
Enumeration<NetworkInterface> nic = NetworkInterface.getNetworkInterfaces();
while (nic.hasMoreElements()) {
NetworkInterface n = nic.nextElement();
// MACアドレスをbyte[]で取得
byte[] addressByte = n.getHardwareAddress();
// 取得したMACアドレスをStringへ変換
nicaddr = "";
if (addressByte != null) {
for (byte b : addressByte) {
nicaddr = nicaddr + String.format("%02X", b);
}
}
map.put(n.getName(),nicaddr);
}
return map;
}
}
@narita1980
Copy link
Author

【実行結果サンプル】
lo :
tun2 : 2B0BA18C
eth1 : 0024A57F3F27
tun1 :
tun0 : FFFFFFFFFFFFFFFF
eth0 : 002318B2E545

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment