java如何获取公网ip,有通过路由
1个回答
展开全部
如果要通过路由器,不同的路由器的获取方法不一样。通用的做法是通过 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("<span\\sclass=\"c-gap-right\">本机IP: ([^<]+)</span>");
Matcher matcher = pattern.matcher(html);
if (matcher.find()) {
String ip = matcher.group(1);
System.out.println(ip);
}
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询