Java 獲得MAC地址

import java.io.*;

public class  GetMac
{
    //通過IP獲取網卡地址
 public String getMacByIP(String serverIP)
 {
  String str = "";
  String macAddress = "";
  try
  {
   
   Process pp = Runtime.getRuntime().exec("nbtstat -A "+serverIP);
   InputStreamReader ir = new InputStreamReader(pp.getInputStream());
   LineNumberReader input = new LineNumberReader(ir);
   for(int i = 1;i < 100;i++)
   {
    str = input.readLine();
    if(str != null) 
    {
     if(str.indexOf("MAC Address") > 1) 
     {
      macAddress = str.substring(str.indexOf("MAC Address")+14,str.length());
      break;
     }
    }
   }
  }
  catch(IOException ex)
  {
   ex.printStackTrace(); 
  }
  return macAddress;
 }
  //通過機器名獲取網卡地址
 public String getMacByServerName(String serverName)
 {
  String str = "";
  String macAddress = "";
  try
  {
   
   Process pp = Runtime.getRuntime().exec("nbtstat -a "+serverName);
   InputStreamReader ir = new InputStreamReader(pp.getInputStream());
   LineNumberReader input = new LineNumberReader(ir);
   for(int i = 1;i < 100;i++)
   {
    str = input.readLine();
    if(str != null) 
    {
     if(str.indexOf("MAC Address") > 1) 
     {
      macAddress = str.substring(str.indexOf("MAC Address")+14,str.length());
      break;
     }
    }
   }
  }
  catch(IOException ex)
  {
   ex.printStackTrace(); 
  }
  return macAddress;
 }


        public static void main(String[] args)
        {
        GetMac getmac;
        getmac=new GetMac();
        String mac="";
        mac=getmac.getMacByIP("172.16.0.1");
        System.out.println(mac);
        mac=getmac.getMacByServerName("server");
        System.out.println(mac);
        }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章