您的位置:首页 > 理论基础 > 计算机网络

java获取系统网络端口IP

2015-01-24 17:01 615 查看
根据系统的不同获取对应得网络端口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;
	   }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐