java 本机ip

        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;
	}

 

你可能感兴趣的:(java)