All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.gitee.fufu669.utils.CacheNetworkUtil Maven / Gradle / Ivy

There is a newer version: 6.666.66021
Show newest version
package com.gitee.fufu669.utils;

import java.net.*;
import java.util.Enumeration;

import javax.servlet.http.HttpServletRequest;

import com.gitee.fufu669.common.CacheKeyCommon;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/** @author wangfupeng */
public class CacheNetworkUtil {

	public static final Logger logger = LoggerFactory.getLogger(CacheNetworkUtil.class);

	public final static String getIpAddr(HttpServletRequest request) {
		/* 获取请求主机IP地址,如果通过代理进来,则透过防火墙获取真实IP地址*/
		String ip = request.getHeader("X-Forwarded-For");
		if (ip == null || ip.length() == 0 || CacheKeyCommon.IP_UNKNOWN.equalsIgnoreCase(ip)) {
			if (ip == null || ip.length() == 0 || CacheKeyCommon.IP_UNKNOWN.equalsIgnoreCase(ip)) {
				ip = request.getHeader("Proxy-Client-IP");
			}
			if (ip == null || ip.length() == 0 || CacheKeyCommon.IP_UNKNOWN.equalsIgnoreCase(ip)) {
				ip = request.getHeader("WL-Proxy-Client-IP");
			}
			if (ip == null || ip.length() == 0 || CacheKeyCommon.IP_UNKNOWN.equalsIgnoreCase(ip)) {
				ip = request.getHeader("HTTP_CLIENT_IP");
			}
			if (ip == null || ip.length() == 0 || CacheKeyCommon.IP_UNKNOWN.equalsIgnoreCase(ip)) {
				ip = request.getHeader("HTTP_X_FORWARDED_FOR");
			}
			if (ip == null || ip.length() == 0 || CacheKeyCommon.IP_UNKNOWN.equalsIgnoreCase(ip)) {
				ip = request.getRemoteAddr();
				if(ip!=null) {
                    if (CacheKeyCommon.IP_127_0_0_1.equals(ip) || CacheKeyCommon.IP_0_0_0_0_0_0_0_1.equals(ip)) {
                        /* 根据网卡取本机配置的IP*/
                        InetAddress inet = null;
                        try {
                            inet = InetAddress.getLocalHost();
                        } catch (UnknownHostException e) {
                            logger.info(e.getMessage(), e);
                        }
                        ip = inet.getHostAddress();
                    }
                }else{
                    InetAddress inet = null;
                    try {
                        inet = InetAddress.getLocalHost();
                    } catch (UnknownHostException e) {
                        logger.info(e.getMessage(), e);
                    }
                    if(inet!=null) {
                        ip = inet.getHostAddress();
                    }
                }
			}
		} else if (ip.length() > CacheKeyCommon.IP_DEFAULT_LENGTH) {
			String[] ips = ip.split(",");
			for (int index = 0; index < ips.length; index++) {
				String strIp = (String) ips[index];
				if (!(CacheKeyCommon.IP_UNKNOWN.equalsIgnoreCase(strIp))) {
					ip = strIp;
					break;
				}
			}
		}
		return ip;
	}

	public final static String getServerIpForWindows(){
		// 获取操作系统类型
		String sysType = System.getProperties().getProperty("os.name");
		String ip;
		if (sysType.toLowerCase().startsWith("win")) {  // 如果是Windows系统,获取本地IP地址
			String localIP = null;
			try {
				localIP = InetAddress.getLocalHost().getHostAddress();
			} catch (UnknownHostException e) {
				logger.error(e.getMessage(), e);
			}
			if (localIP != null) {
				return localIP;
			}
		}
		return "获取服务器IP错误";
	}

	/**
	 * 根据网络接口获取IP地址
	 * @param ethNum 网络接口名,Linux下是eth0
	 * @return
	 */
	public final static String getServerIpByEthNumForLinux(String ethNum ) {
		try {
			Enumeration allNetInterfaces = NetworkInterface.getNetworkInterfaces();
			InetAddress ip;
			while (allNetInterfaces.hasMoreElements()) {
				NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement();
				if (ethNum.equals(netInterface.getName())) {
					Enumeration addresses = netInterface.getInetAddresses();
					while (addresses.hasMoreElements()) {
						ip = (InetAddress) addresses.nextElement();
						if (ip != null && ip instanceof Inet4Address) {
							return ip.getHostAddress();
						}
					}
				}
			}
		} catch (SocketException e) {
			logger.error(e.getMessage(), e);
		}
		return "获取服务器IP错误";
	}

	public static String getLocalServerIP() throws UnknownHostException, SocketException {
		if (isWindowsOS()) {
			return InetAddress.getLocalHost().getHostAddress();
		} else {
			return getLinuxLocalIp();
		}
	}

	/**
	 * 判断操作系统是否是Windows
	 *
	 * @return
	 */
	public static boolean isWindowsOS() {
		boolean isWindowsOS = false;
		String osName = System.getProperty("os.name");
		if (osName.toLowerCase().indexOf("windows") > -1) {
			isWindowsOS = true;
		}
		return isWindowsOS;
	}

	/**
	 * 获取本地Host名称
	 */
	public static String getLocalHostName() throws UnknownHostException {
		return InetAddress.getLocalHost().getHostName();
	}

	/**
	 * 获取Linux下的IP地址
	 *
	 * @return IP地址
	 * @throws SocketException
	 */
	private static String getLinuxLocalIp() throws SocketException {
		String ip = "";
		try {
			for (Enumeration en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
				NetworkInterface intf = en.nextElement();
				String name = intf.getName();
				if (!name.contains("docker") && !name.contains("lo")) {
					for (Enumeration enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
						InetAddress inetAddress = enumIpAddr.nextElement();
						if (!inetAddress.isLoopbackAddress()) {
							String ipaddress = inetAddress.getHostAddress().toString();
							if (!ipaddress.contains("::") && !ipaddress.contains("0:0:") && !ipaddress.contains("fe80")) {
								ip = ipaddress;
							}
						}
					}
				}
			}
		} catch (SocketException ex) {
			ip = "127.0.0.1";
		}
		return ip;
	}

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy