通过Java获取本地主机的外网地址, 该实验通过网址chinaz获取。
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Created with IntelliJ IDEA.
* Description:
*
* @author: SweiPC
* @data: 2022-09-18 12:06
*/
public class GetHostIP {
public static void main(String[] args) throws IOException {
String ip = null;
String chinaz = "https://ip.chinaz.com";
StringBuilder inputLine = new StringBuilder();
String read = "";
URL url = null;
HttpURLConnection urlConnection = null;
BufferedReader in = null;
try {
url = new URL(chinaz);
urlConnection = (HttpURLConnection) url.openConnection();
in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "UTF-8"));
while ((read = in.readLine()) != null) {
inputLine.append(read + "\r\n");
}
Pattern p = Pattern.compile("\\<dd class\\=\"fz24\">(.*?)\\<\\/dd>");
Matcher m = p.matcher(inputLine.toString());
if (m.find()) {
String ipstr = m.group(1);
ip = ipstr;
}
} finally {
if (in != null) {
in.close();
}
}
if (ip == null) {
throw new RuntimeException();
}
System.out.println(ip);
}
}