JAVA获取本地外网IP
最近搞物联网平台,发现终端的设备在插拔网线之后,IP发生了改变导致,平台无法连接,遂想出个办法,在终端执行一个定时任务发送终端IP到服务平台,
下面是通过java获取外网IP的程序。
package com.fan.study.ip; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.util.regex.Matcher; import java.util.regex.Pattern; public class IPUtil { public static void main(String[] args) throws IOException { System.out.println(IPUtil.getIP()); } /** * @Param * @Description 获取IP * @Date: 2021/5/11 **/ public static String getIP() throws IOException { String ip = null; String chinaZ = "http://ip.chinaz.com"; String response = sendGet(chinaZ); //过滤出响应中外网IP ip = match(response, "\\<dd class\\=\"fz24\">(.*?)\\<\\/dd>"); if (ip == null) { String newUrl = match(response, "window.location.href=\"(http://ip.chinaz.com.+)\""); response = sendGet(newUrl); ip = match(response, "\\<dd class\\=\"fz24\">(.*?)\\<\\/dd>"); } return ip; } /** * @Param str * @Param regex * @Description 正则过滤 * @Date: 2021/5/11 **/ public static String match(String str, String regex) { Pattern p = Pattern.compile(regex); Matcher m = p.matcher(str); if (m.find()) { return m.group(1); } return null; } /** * @Param url * @Description 发送get请求 * @Date: 2021/5/11 **/ public static String sendGet(String url) throws IOException { URL urlObject = new URL(url); HttpURLConnection connection = (HttpURLConnection) urlObject.openConnection(); connection.connect(); try (InputStream inputStream = connection.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) { StringBuilder response = new StringBuilder(); String str; while ((str = reader.readLine()) != null) { response.append(str); } return response.toString(); } catch (Exception ex) { ex.printStackTrace(); } return null; } }