Java獲取本機名稱、本機MAC地址、IP地址
阿新 • • 發佈:2018-11-04
Java獲取本機名稱、本機MAC地址、IP地址
public class Test { public static void main(String[] args) throws Exception { InetAddress ia=null; try { ia=ia.getLocalHost(); String localname=ia.getHostName(); String localip=ia.getHostAddress(); System.out.println("本機名:"+ localname); System.out.println("本機ip:"+localip); } catch (Exception e) { e.printStackTrace(); } InetAddress ia1 = InetAddress.getLocalHost();//獲取本地IP物件 System.out.println("MAC ."+getMACAddress(ia1)); } //獲取MAC地址的方法 private static String getMACAddress(InetAddress ia)throws Exception{ byte[] mac = NetworkInterface.getByInetAddress(ia).getHardwareAddress();//獲得網路介面物件(即網絡卡),並得到mac地址,mac地址存在於一個byte陣列中。 StringBuffer sb = new StringBuffer(); //下面程式碼是把mac地址拼裝成String for(int i=0;i<mac.length;i++){ if(i!=0){ sb.append("-"); } String s = Integer.toHexString(mac[i] & 0xFF); //mac[i] & 0xFF 是為了把byte轉化為正整數 System.err.println(s); sb.append(s.length()==1?0+s:s); } return sb.toString().toUpperCase(); //把字串所有小寫字母改為大寫成為正規的mac地址並返回 } }