Recently in doing an app, which has a function point is to get the computer's extranet IP, the vast majority of the Internet is to obtain the LAN IP method, some seem to be able to obtain the extranet IP method but also has failed.
Most of the references are
ip = Inetaddress.getlocalhost (). gethostaddress ();
Or
inetaddress[] Inetadds = Inetaddress.getallbyname (inetaddress. Getlocalhost (). GetHostName ());
Obviously, get is not the external network address, also not clear marked with the external network IP heroes are how to get the conclusion of the extranet IP.
A possible way to get the IP field out of the Web site is through an HTTP request. For example: http://ip.chinaz.com/
This URL, combined with a simple regular expression, is available.
View the HTML code for this section through Firefox as follows:
Get a string between [<strong class= "Red"]</strong> through a regular expression
The code is as follows:
public static String Getv4ip () {
String IP = "";
String Chinaz = "http://ip.chinaz.com/";
String inputline = "";
String read = "";
try {
URL url = new URL (Chinaz);
HttpURLConnection URLConnection = (httpurlconnection) url.openconnection ();
BufferedReader in = new BufferedReader (New InputStreamReader (Urlconnection.getinputstream ()));
while (read = In.readline ())!= null) {
Inputline + = read;
}
System.out.println (Inputline);
catch (Exception e) {
E.printstacktrace ();
}
Pattern p = pattern.compile ("\\<strong class\\=\" red\ "> (. *?) \\<\\/strong> ");
Matcher m = P.matcher (Inputline);
if (M.find ()) {
String ipstr = M.group (1);
System.out.println (IPSTR);
}
return IP;
}