现在的位置: 首页 > 综合 > 正文

java获取系统网络端口IP

2019年07月16日 ⁄ 综合 ⁄ 共 1010字 ⁄ 字号 评论关闭

根据系统的不同获取对应得网络端口IP

/**
	 * 判断是否为windows
	 * @return
	 */
	 private boolean isWindowsOS() {
	       boolean isWindowsOS = false;
	       String osName = System.getProperty("os.name");
	       if (osName.toLowerCase().indexOf("windows") > -1) {
	           isWindowsOS = true;
	       }
	       return isWindowsOS;
	   }


	   /**
	    * 获取本机IP地址,并自动区分Windows还是Linux操作系统
	    * @return
	    */
	  private String getLocalIP() {
	       String sIP = "";
	       InetAddress ip = null;
	       try {
	           // 如果是Windows操作系统
	           if (isWindowsOS()) {
	        	   sIP = InetAddress.getLocalHost().getHostAddress();
	           }
	           // 如果是Linux操作系统
	           else {
	        	   Enumeration<NetworkInterface> netInterfaces = (Enumeration<NetworkInterface>) NetworkInterface
	                        .getNetworkInterfaces();
	                netInterfacesWhile : while (netInterfaces.hasMoreElements()) {
	                	NetworkInterface ni = (NetworkInterface) netInterfaces.nextElement();
	                	log.debug("网络端口名称:" + ni.getName());
                		Enumeration<?> e2 = ni.getInetAddresses();
                		while (e2.hasMoreElements()) {
	                		ip = (InetAddress) e2.nextElement();
	                		if ((ip instanceof Inet4Address) && !"127.0.0.1".equals(ip.getHostAddress())){
	                			sIP = ip.getHostAddress();
	                			log.debug("获得的IP是:" + sIP);
	                			break netInterfacesWhile;
	                		}
                		}
	                }
	           }
	       } catch (Exception e) {
	           log.error("获取本机IP异常",e);
	       }
	       return sIP;
	   }

抱歉!评论已关闭.