java获取本机外网ip

参考了一些博客,发现大部分都是通过访问外网再进行获取外网ip,本文是通过访问chinaz的接口返回的ip信息直接获取,有更好的办法可以指教一下,感谢!

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;

import sun.net.www.protocol.http.HttpURLConnection;

public class IP {
	public static String getIP() {
		String ip = "http://ip.chinaz.com/getip.aspx";

		String inputLine = "";
		String read = "";
		try {
			URL url = new URL(ip);
			HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
			BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
			while ((read = in.readLine()) != null) {
			inputLine += read;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return inputLine;
	}
	public static void main(String[] args) {
		System.out.println(getIP());
	}
}

阅读更多

没有更多推荐了,返回首页