java获取本机外网IP地址 内网IP地址


java获取本机外网IP地址

第一种方法

思路是访问[http://1212.ip138.com/ic.asp],根据返回结果来得到外网IP地址。

	public static String getOuterIp() throws IOException {

		URL url = new URL("http://1212.ip138.com/ic.asp");

		BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream()));

		String s = "";

		StringBuffer sb = new StringBuffer("");

		String webContent = "";

		while ((s = br.readLine()) != null) {
			sb.append(s + "\r\n");

		}

		br.close();
		webContent = sb.toString();
		int start = webContent.indexOf("[") + 1;
		int end = webContent.indexOf("]");
		webContent = webContent.substring(start, end);

		return webContent;
	}

第二种方法

只适用于LINUX系统。

	
	public static String getOuterIpForLinux() throws IOException {
		boolean bFindIP = false;
		InetAddress ip = null;
		Enumeration<NetworkInterface> netInterfaces = 
			(Enumeration<NetworkInterface>) NetworkInterface.getNetworkInterfaces();
		while (netInterfaces.hasMoreElements()) {
			if (bFindIP) {
				break;
			}
			NetworkInterface ni = (NetworkInterface) netInterfaces.nextElement();
			// 遍历所有IP
			Enumeration<InetAddress> ips = ni.getInetAddresses();
			while (ips.hasMoreElements()) {
				ip = (InetAddress) ips.nextElement();
				if (!ip.isSiteLocalAddress() && !ip.isLoopbackAddress() 
						&& ip.getHostAddress().indexOf(":") == -1) {//获取外网IP
					bFindIP = true;
					break;
				}
			}
		}
		
		return ip.getHostAddress();
	}
	


java获取本机内网IP地址-局域网IP地址

	
	public String getInnerIp() {

		String sIP = "";
		InetAddress ip = null;
		try {
			// 如果是Windows操作系统
			if (isWindowsOS()) {
				ip = InetAddress.getLocalHost();
			}
			// 如果是Linux操作系统
			else {
				boolean bFindIP = false;
				Enumeration<NetworkInterface> netInterfaces = 
					(Enumeration<NetworkInterface>) NetworkInterface.getNetworkInterfaces();
				while (netInterfaces.hasMoreElements()) {
					if (bFindIP) {
						break;
					}
					NetworkInterface ni = (NetworkInterface) netInterfaces.nextElement();
					// 遍历所有ip
					Enumeration<InetAddress> ips = ni.getInetAddresses();
					while (ips.hasMoreElements()) {
						ip = (InetAddress) ips.nextElement();
						if (ip.isSiteLocalAddress() && !ip.isLoopbackAddress()
								&& ip.getHostAddress().indexOf(":") == -1) {// 获取内网IP地址
							bFindIP = true;
							break;
						}
					}

				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		if (null != ip) {
			sIP = ip.getHostAddress();
		}
		return sIP;
	}

	// 获取系统类型
	public boolean isWindowsOS() {
		boolean isWindowsOS = false;
		String osName = System.getProperty("os.name");
		if (osName.toLowerCase().indexOf("windows") > -1) {
			isWindowsOS = true;
		}
		return isWindowsOS;
	}
				



联系我们 | 友情链接