Sometimes it's useful to know what the outside world sees as your IP address when you're behind a router, maybe using NAT. You can do this by asking the site whatismyip.com. The following is a way to do that and the current recommended website address is used. Make sure it's still valid before you rely on this code as the targeted site can change suddenly. You might need to adjust the regex from time to time. It's HERE
import java.io.*;
import java.net.*;
public class WIMI {
public final static String WIP_SITE = "http://whatsmyip.net";
private final static String REPLACE_PATTERN = "(?s).*?(\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}).*";
// For demo
public static void main(String[] args) {
System.out.println(WIMI.whatIsMyIp());
}
public static String whatIsMyIp() {
String result = null;
InputStream in = null;
try {
URLConnection conn = new URL(WIP_SITE).openConnection();
int length = Integer.valueOf(conn.getHeaderField("Content-Length"));
byte[] buf = new byte[length];
in = conn.getInputStream();
in.read(buf);
result = new String(buf);
result = result.replaceAll(REPLACE_PATTERN, "$1");
} catch (IOException e) {
e.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) { /* ignore */
}
}
}
return result;
}
}
import java.net.*;
public class WIMI {
public final static String WIP_SITE = "http://whatsmyip.net";
private final static String REPLACE_PATTERN = "(?s).*?(\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}).*";
// For demo
public static void main(String[] args) {
System.out.println(WIMI.whatIsMyIp());
}
public static String whatIsMyIp() {
String result = null;
InputStream in = null;
try {
URLConnection conn = new URL(WIP_SITE).openConnection();
int length = Integer.valueOf(conn.getHeaderField("Content-Length"));
byte[] buf = new byte[length];
in = conn.getInputStream();
in.read(buf);
result = new String(buf);
result = result.replaceAll(REPLACE_PATTERN, "$1");
} catch (IOException e) {
e.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) { /* ignore */
}
}
}
return result;
}
}