Java 获取Windows IP配置等信息

本文介绍如何使用Java编程语言获取本机的IP地址、主机名、子网掩码及MAC地址等网络信息,并提供了一段示例代码进行详细说明。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一般都是获取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();
	}

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值