最近在做一个app,其中有一个功能点是获取本机的外网ip,网上流传的绝大部分都是获取局域网ip的方法,有些似乎能够获取外网ip方法但也已经失效。
大部分提到的都是
ip = InetAddress.getLocalHost().getHostAddress();
或者
InetAddress[] inetAdds = InetAddress.getAllByName(InetAddress .getLocalHost().getHostName());
显然,得到的不是外网地址,也不清楚标着外网ip的各位大侠都是怎么得到获取的是外网ip的结论的。
一种可行的获取方法,是通过http请求从网站中取出ip字段。例如:http://ip.chinaz.com/
通过这个网址,加上简单的正则表达式,即可得到。
通过正则表达式获取[之间的字符串即可
代码如下:
public static String getV4IP() {
String ip = "";
String chinaz = "http://ip.chinaz.com/";
String inputLine = "";
String read = "";
try {
URL url = new URL(chinaz);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
while ((read = in.readLine()) != null) {
inputLine += read;
}
System.out.println(inputLine);
} catch (Exception e) {
e.printStackTrace();
}
Pattern p = Pattern.compile("\\(.*?)\\<\\/strong>");
Matcher m = p.matcher(inputLine);
if(m.find()){
String ipstr = m.group(1);
System.out.println(ipstr);
}
return ip;
}