这篇文章将为大家详细讲解有关JAVA中怎么获取本机的公网IP,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。
代码如下
public static String getV4IP() { String ip = ""; String chinaz = "ht" + "tp" + ":/" + "/i" + "p.ch" + "in" + "az." + "co" + "m"; 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"); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (in != null) { try { in.close(); } catch (IOException e) { e.printStackTrace(); } } } Pattern p = Pattern.compile("\\<dd class\\="\"fz24\"">(.*?)\\<\\/dd>"); Matcher m = p.matcher(inputLine.toString()); if (m.find()) { String ipstr = m.group(1); ip = ipstr; } return ip; }
调用该方法,返回字符串:
关于JAVA中怎么获取本机的公网IP就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。