java获取系统网络端口IP

根据系统的不同获取对应得网络端口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;
	   }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值