在平时,如果想获取本机的公网IP,我们都知道去百度查询一下,它就会出来。
但是在代码中,如果获取到本机的公网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>");Matcher m = p.matcher(inputLine.toString());
if (m.find()) {
String ipstr = m.group(1);
ip = ipstr;
}
return ip;
}
调用该方法,返回字符串:
该方法粘贴过去直接用,返回的就是本机公网IP
其原理很简单,向chinaz网站发送请求,chinaz网站会把请求的公网IP返回过来,然后我们经过一些简单的处理,就可以得到公网IP了。