Java 读取本机IP地址

    今天要跟大家分享的是,一个读取本机ip地址的方法。

	private  List<String> getLocalIps() {
		ArrayList<String> allIP = new ArrayList<String>();
		Enumeration<NetworkInterface> netInterfaces = null;
		try {
			netInterfaces = NetworkInterface.getNetworkInterfaces();
			while (netInterfaces.hasMoreElements()) {
				NetworkInterface ni = netInterfaces.nextElement();
				Enumeration<InetAddress> ips = ni.getInetAddresses();

				while (ips.hasMoreElements()) {
					String ip = ips.nextElement().getHostAddress();
					if (ip.equalsIgnoreCase("127.0.0.1")) {
						continue;
					}
					allIP.add(ip);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return allIP;
	}

 

   注意,本机可能有多个IP地址,故返回的是一个String的List.

你可能感兴趣的:(java)