`

java 本机ip

    博客分类:
  • java
 
阅读更多
        String ip = null;
        try {
        	ip = InetAddress.getLocalHost().getHostAddress().toString();//winXP
		} catch (UnknownHostException e) {
			log.error("获取本机ip失败", e);
		}
        if(StringUtils.isBlank(ip)){
    		ip = getLocalIP();//linux
    	}
		log.info("本机ip="+ip);

 

 

 

    
	private String getLocalIP() {
		String ip = "";
		try {
			Enumeration<?> e1 = (Enumeration<?>) NetworkInterface
					.getNetworkInterfaces();
			while (e1.hasMoreElements()) {
				NetworkInterface ni = (NetworkInterface) e1.nextElement();
				if (!ni.getName().equals("eth0")) {
					continue;
				} else {
					Enumeration<?> e2 = ni.getInetAddresses();
					while (e2.hasMoreElements()) {
						InetAddress ia = (InetAddress) e2.nextElement();
						if (ia instanceof Inet6Address)
							continue;
						ip = ia.getHostAddress();
					}
					break;
				}
			}
		} catch (SocketException e) {
			e.printStackTrace();
			System.exit(-1);
		}
		return ip;
	}

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics