Principle: First access to http://1212.ip138.com/ic.asp to get the local public network IP, and then use Jsoup to extract IP from the IP results page.
Add the Jsoup package to the project.
The code is as follows:
Package main;
Import java.io.IOException;
Import java.net.InetAddress;
Import java.net.UnknownHostException;
Import org.jsoup.Connection;
Import Org.jsoup.Jsoup; public class Main {/** * gets native extranet IP and returns local IP * @return/private static string Getpublicip () {String IP =
Null
try {IP = inetaddress.getlocalhost (). gethostaddress ();
catch (Unknownhostexception e) {e.printstacktrace ();
} org.jsoup.nodes.Document doc = null;
Connection con = null;
Connection http://1212.ip138.com/ic.asp con = jsoup.connect ("http://1212.ip138.com/ic.asp"). Timeout (10000);
try {doc = Con.get ();
Get a text string containing native IP: Your IP is: [xxx.xxx.xxx.xxx] From: YY org.jsoup.select.Elements els = doc.body (). Select ("Center");
for (org.jsoup.nodes.Element el:els) {IP = El.text ();
///filter out the IP from the text string, and the regular expression will be non-numeric and. Replace with null string "" IP = Ip.replaceall ("[^0-9.]", "");
catch (IOException e) {e.printstacktrace ();
return IP;
} return IP; } public Static void Main (string[] args) {String str = GETPUBLICIP ();
System.out.println (str);
}
}