Created
July 6, 2012 02:22
-
-
Save narita1980/3057659 to your computer and use it in GitHub Desktop.
NetworkInterfaceを使いMACアドレスを取得する(要JDK1.6以上)
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.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; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
【実行結果サンプル】
lo :
tun2 : 2B0BA18C
eth1 : 0024A57F3F27
tun1 :
tun0 : FFFFFFFFFFFFFFFF
eth0 : 002318B2E545