java 获取本机的公网、外网ip

本机通过路由器联网,获取ip时获取的是路由器分配的IP。

获取公网的IP:

先找一个网站,可以获得本机的外网IP,如http://www.ip138.com/

java 获取本机的公网、外网ip_第1张图片

检查元素,可以获得一个地址

java 获取本机的公网、外网ip_第2张图片


直接访问这个网站进行截取

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.SocketException;
import java.net.URL;
import java.net.URLConnection;

public class Main {

	public static void main(String[] args) throws SocketException {
		for (int i = 0; i < 1000000; i++) {
			int a=i;
			new Runnable() {
				public void run() {
					System.out.println(a+"=========="+Main.getMyIP());
				}
			}.run();
		}
	}

	private static String getMyIP() {
		InputStream ins = null;
		try {
			URL url = new URL("http://1212.ip138.com/ic.asp");
			URLConnection con = url.openConnection();
			ins = con.getInputStream();
			InputStreamReader isReader = new InputStreamReader(ins, "GB2312");
			BufferedReader bReader = new BufferedReader(isReader);
			StringBuffer webContent = new StringBuffer();
			String str = null;
			while ((str = bReader.readLine()) != null) {
				webContent.append(str);
			}
//			System.out.println(webContent);
			int start = webContent.indexOf("[") + 1;
			int end = webContent.indexOf("]");
			return webContent.substring(start, end);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (ins != null) {
				try {
					ins.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return "";
	}  
}



你可能感兴趣的:(java 获取本机的公网、外网ip)