java代码如何获取本机外网IP地址呢?
下文笔者讲述使用java代码获取本机的外网IP地址的方法分享,如下所示
然后返回外网IP地址
Java中获取本机的外网IP地址呢
实现思路: 使用http访问去指定网址即可获取本机的外网IP地址
获取本地IP地址的方法
public static String getLocalAddress(){ String ip = ""; try { ip = InetAddress.getLocalHost().getHostAddress(); } catch (UnknownHostException e) { e.printStackTrace(); } //本机IP地址 return ip; }
获取外网本机的IP地址的方法
此处我们需借助 去http://ip.chinaz.com/请求然后返回外网IP地址
public static String getIPV4(){ String ip = ""; String chinaz = "http://ip.chinaz.com"; 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"); } //System.out.println(inputLine.toString()); } 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地址呢
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。