java获取外网ip

阅读更多

 * 获取本机外网IP地址。 

 * 实现方法是访问网站http://1212.ip138.com/ic.asp,

 * 得到返回的文本后解析出本机在外网的IP地址。

 

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 获取本机外网IP地址。 
 * 实现方法是访问网站http://1212.ip138.com/ic.asp,
 * 得到返回的文本后解析出本机在外网的IP地址。
 * 
 * @author cyn
 * 
 */
public class ExternalIpAddressFetcher {
	// 本机外网IP地址
	private String myExternalIpAddress;

	public ExternalIpAddressFetcher(String externalIpProviderUrl) {
		fetchExternalIpProviderHTML(externalIpProviderUrl);
	}

	/**
	 * 从http://checkip.dyndns.org返回的字符串中通过正则表达式提取外网ip
	 * 
	 * @param externalIpProviderUrl
	 * @return
	 */
	private String fetchExternalIpProviderHTML(String externalIpProviderUrl) {
		// 输入流
		InputStream ins = null;

		// 到外网提供者的Http连接
		URLConnection httpConn = null;

		try {
			// 打开连接
			URL url = new URL(externalIpProviderUrl);
			httpConn = url.openConnection();

			ins = httpConn.getInputStream();
			InputStreamReader isReader = new InputStreamReader(ins, "GB2312");
			BufferedReader bReader = new BufferedReader(isReader);
			StringBuffer webContent = new StringBuffer();
			String str = null;
			while ((str = bReader.readLine()) != null) {
				if (parse(str)) {
					webContent.append(str);
					break;
				}
			}
			// 返回
			return webContent.toString();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				ins.close();
			} catch (Exception ex) {
				ex.printStackTrace();
			}
		}

		// 出现异常则返回空
		return null;
	}

	/**
	 * 使用正则表达式解析返回的HTML文本,得到本机外网地址
	 * 
	 * @param html
	 */
	private boolean parse(String html) {
		boolean ret = false;
		Pattern pattern = Pattern.compile("(\\d{1,3})[.](\\d{1,3})[.](\\d{1,3})[.](\\d{1,3})",
				Pattern.CASE_INSENSITIVE);
		Matcher matcher = pattern.matcher(html);
		while (matcher.find()) {
			myExternalIpAddress = matcher.group(0);
			ret = true;
			break;
		}
		return ret;
	}

	/**
	 * 得到本机外网地址,得不到则为空
	 * 
	 * @return
	 */
	public String getMyExternalIpAddress() {
		return myExternalIpAddress;
	}

	public static void main(String[] args) {
		ExternalIpAddressFetcher fetcher = new ExternalIpAddressFetcher("http://1212.ip138.com/ic.asp");

		System.out.println(fetcher.getMyExternalIpAddress());
	}
}

 

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