2012-10-05 234 views
3

我正在開發一個軟件,我需要通過java代碼的計算機的IP地址和MAC地址列表。有沒有辦法獲得IP地址和MAC地址列表?如何通過java獲取計算機的MAC地址和IP地址列表?

感謝

+3

您必須在互聯網上搜索的在發佈問題前回答。 http://www.mkyong.com/java/how-to-get-mac-address-in-java/ 希望有所幫助。 –

+0

它在本教程中很好地解釋了...請參閱此鏈接http://www.mkyong.com/java/how-to-get-mac-address-in-java/ –

回答

7

由於JDK 1.6,Java開發人員能夠通過NetworkInterface類訪問網卡的細節。

  InetAddress ip; 
    ip = InetAddress.getLocalHost(); 
    System.out.println("Current IP address : " + ip.getHostAddress()); 

    NetworkInterface network = NetworkInterface.getByInetAddress(ip); 

    byte[] mac = network.getHardwareAddress(); 

    System.out.print("Current MAC address : "); 

    StringBuilder sb = new StringBuilder(); 
    for (int i = 0; i < mac.length; i++) { 
     sb.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : ""));   
    } 
    System.out.println(sb.toString()); 

多個IP地址:

    java.util.Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); 
     en.hasMoreElements();) { 
     NetworkInterface iface = en.nextElement(); 
     List<InterfaceAddress> addrs = iface.getInterfaceAddresses(); 
     //For each network interfaces iterate through each ip address 
     for(InterfaceAddress addr : addrs) { 
         ip = addr.getAddress(); 
          //Process the IP ... 
+0

此代碼適用於單個IP計算機,但如果一臺計算機中有多個IP地址會怎麼樣。 – Deval

+1

@Deval請參閱最新的答案... – aleroot

+0

請問您可以用大括號正確地發佈更新後的答案 – Deval

1

示例代碼運行從java程序的命令,

Process p; 
    String cmd="ifconfig-a"; 
    p = Runtime.getRuntime().exec(cmd); 
    BufferedReader br = new BufferedReader(
    new InputStreamReader(p.getInputStream())); 
    while ((s = br.readLine()) != null) 
    System.out.println("line: " + s); 
    p.waitFor(); 
    System.out.println ("exit: " + p.exitValue()); 
    p.destroy(); 

輸出:

line: eth0  Link encap:Ethernet HWaddr 00:13:D3:DE:5A:A4 --->MAC address in linux 
+1

它僅適用於Windows ... – aleroot

+0

您能否定義什麼是p變量 – Deval