展开全部
如果要通过路由器,不同的路由器的获取方法不一样。通用的做法32313133353236313431303231363533e78988e69d8331333365656636是通过 HttpClient 在百度上搜索关键字 ip, 然后提取出公网ip。
代码如下:import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class App {
// 获取网页源码
static String httpGet(String url) {
StringBuffer buffer = new StringBuffer();
try {
URLConnection conn = new URL(url).openConnection();
conn.addRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36");
try (InputStream inputStream = conn.getInputStream();
InputStreamReader streamReader = new InputStreamReader(inputStream);
BufferedReader reader = new BufferedReader(streamReader);) {
String line = null;
while ((line = reader.readLine()) != null) {
buffer.append(line).append(System.lineSeparator());
}
}
} catch (IOException e) {
e.printStackTrace();
}
return buffer.toString();
}
public static void main(String[] args) {
String html = httpGet("https://www.baidu.com/s?wd=ip");
// 提出IP
Pattern pattern = Pattern.compile("本机IP: ([^");
Matcher matcher = pattern.matcher(html);
if (matcher.find()) {
String ip = matcher.group(1);
System.out.println(ip);
}
}
}