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();
	}

如果有获取这个名字的方法,请指教。谢谢。

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