Here you can find the source of getExternalIP(String host, String regexPattern)
Parameter | Description |
---|---|
host | remote host |
regexPattern | pattern of response, ip address pattern should be in group, e.g. <b>.+<body>Current IP Address: (\\d+.\\d+.\\d+.\\d+)</body>.+</b> |
public static String getExternalIP(String host, String regexPattern)
//package com.java2s; //License from project: Open Source License import java.net.HttpURLConnection; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Main { /**//from w w w . j ava 2s . c om * Finds external IP address by sending http request to <b>host</b> with expected response in pattern <b>regexPattern</b> * @param host remote host * @param regexPattern pattern of response, ip address pattern should be in group, e.g. <b>.+<body>Current IP Address: (\\d+.\\d+.\\d+.\\d+)</body>.+</b> * @return IP address if matched with regexPattern */ public static String getExternalIP(String host, String regexPattern) { String resp = null; if (regexPattern == null) regexPattern = ".+<body>Current IP Address: (\\d+.\\d+.\\d+.\\d+)</body>.+"; if (host == null) host = "http://checkip.dyndns.org:8245/"; Pattern pattern = Pattern.compile(regexPattern); try { java.net.URL URL = new java.net.URL(host); java.net.HttpURLConnection conn = (HttpURLConnection) URL.openConnection(); conn.setConnectTimeout(60000); conn.setReadTimeout(60000); java.io.InputStream InStream = conn.getInputStream(); java.io.InputStreamReader Isr = new java.io.InputStreamReader(InStream); java.io.BufferedReader br = new java.io.BufferedReader(Isr); resp = br.readLine(); if (resp != null) { Matcher matcher = pattern.matcher(resp); if (matcher.matches()) { return matcher.group(1); } } } catch (Exception e) { // } return resp; } /** * Returns external IP address by sending HTTP request to http://checkip.dyndns.org:8425 * @return external IP address by sending HTTP request to http://checkip.dyndns.org:8425 */ public static String getExternalIP() { return getExternalIP("http://checkip.dyndns.org:8245/", ".+<body>Current IP Address: (\\d+.\\d+.\\d+.\\d+)</body>.+"); } }