1500字范文,内容丰富有趣,写作好帮手!
1500字范文 > java获取本机的外网ip----最简便 易懂

java获取本机的外网ip----最简便 易懂

时间:2019-01-20 22:54:48

相关推荐

java获取本机的外网ip----最简便 易懂

IP/IPv6查询,服务器地址查询 - 站长工具

可以通过上面的网站进行手动查询本机的外网ip

java代码

public class IPUntils {public static String getInterIP1() throws Exception {return InetAddress.getLocalHost().getHostAddress();}public static String getInterIP2() throws SocketException {String localip = null;// 本地IP,如果没有配置外网IP则返回它String netip = null;// 外网IPEnumeration<NetworkInterface> netInterfaces;netInterfaces = NetworkInterface.getNetworkInterfaces();InetAddress ip = null;boolean finded = false;// 是否找到外网IPwhile (netInterfaces.hasMoreElements() && !finded) {NetworkInterface ni = netInterfaces.nextElement();Enumeration<InetAddress> address = ni.getInetAddresses();while (address.hasMoreElements()) {ip = address.nextElement();if (!ip.isSiteLocalAddress() && !ip.isLoopbackAddress() && ip.getHostAddress().indexOf(":") == -1) {// 外网IPnetip = ip.getHostAddress();finded = true;break;} else if (ip.isSiteLocalAddress() && !ip.isLoopbackAddress() && ip.getHostAddress().indexOf(":") == -1) {// 内网IPlocalip = ip.getHostAddress();}}}if (netip != null && !"".equals(netip)) {return netip;} else {return localip;}}public static String getOutIPV4() {String ip = "";String chinaz = "";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 = pile("\\<dd class\\=\"fz24\">(.*?)\\<\\/dd>");Matcher m = p.matcher(inputLine.toString());if (m.find()) {String ipstr = m.group(1);ip = ipstr;}return ip;}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。