Android 获取公网IP地址
获取公网IP地址:
/**
* 获取公网IP地址
*/
public static String getIpv4NetIP() {
// 访问返回 IP 地址的网站
URL url;
HttpURLConnection connection;
try {
url = new URL("https://checkip.amazonaws.com/");
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
// 读取网站返回的 IP 地址字符串
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String ipAddress = reader.readLine();
// 关闭连接和输入流
reader.close();
connection.disconnect();
// 提取 IP 地址字符串
String regex = "\\b(?:\\d{1,3}\\.){3}\\d{1,3}\\b";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(ipAddress);
if (matcher.find()) {
return matcher.group();
} else {
return "";
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}