Java get extranet IP address __java

Source: Internet
Author: User

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;
}




Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.