Java 獲取Windows IP配置等信息

一般都是獲取IP,本機名稱,子網掩碼,Mac地址。

一:獲取IP和本機名稱

InetAddress ip = null;
Enumeration<NetworkInterface> allNetInterfaces = NetworkInterface.getNetworkInterfaces();
		while (allNetInterfaces.hasMoreElements()) {
			NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement();
			if (netInterface.isLoopback() || netInterface.isVirtual() || !netInterface.isUp()) {
				continue;
			} else {
				Enumeration<InetAddress> addresses = netInterface.getInetAddresses();
				while (addresses.hasMoreElements()) {
					ip = addresses.nextElement();
					if (ip != null && ip instanceof Inet4Address) {
						System.out.println(ip.getHostAddress());//IP
						System.out.println(ip.getHostName());//本機地址
					}
				}
			}
		}

二:獲取子網掩碼

List<InterfaceAddress> list = ni.getInterfaceAddresses();// 獲取此網絡接口的全部或部分InterfaceAddresses所組成的列表
		if (list.size() > 0) {
			int mask = list.get(0).getNetworkPrefixLength(); // 子網掩碼的二進制1的個數
			StringBuilder maskStr = new StringBuilder();
			int[] maskIp = new int[4];
			for (int i = 0; i < maskIp.length; i++) {
				maskIp[i] = (mask >= 8) ? 255 : (mask > 0 ? (mask & 0xff) : 0);
				mask -= 8;
				maskStr.append(maskIp[i]);
				if (i < maskIp.length - 1) {
					maskStr.append(".");
				}
			}
			System.out.println("SubnetMask:" + maskStr);
		}

三:Mac地址

InetAddress ia = InetAddress.getLocalHost();
// 獲得網絡接口對象(即網卡),並得到mac地址,mac地址存在於一個byte數組中。
byte[] mac = NetworkInterface.getByInetAddress(ia).getHardwareAddress();
// 下面代碼是把mac地址拼裝成String
StringBuffer sb = new StringBuffer();
	for (int i = 0; i < mac.length; i++) {
		if (i != 0) {
			sb.append("-");
		}
		String s = Integer.toHexString(mac[i] & 0xFF);
		sb.append(s.length() == 1 ? 0 + s : s);
	}
	// 把字符串所有小寫字母改爲大寫成爲正規的mac地址並返回
System.out.println(sb.toString().toUpperCase());

四:打印Windows IP配置的信息   cmd ->  ipconfig /all

try {
	Process pro = Runtime.getRuntime().exec("cmd /c ipconfig /all");
	InputStreamReader isr = new InputStreamReader(pro.getInputStream(), "GBK");//需要轉換字符編碼
	BufferedReader br = new BufferedReader(isr);
	String str = br.readLine();
	while (str != null) {
		System.out.println(str.trim());
		str = br.readLine();
		}
		br.close();
		isr.close();
	} catch (Exception e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}

如果有獲取這個名字的方法,請指教。謝謝。

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