Get the website IP corresponding to the request address

1. Add domain name resolution tool class

import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * Domain name resolution tools
 * @author lh
 *
 */
public class DomainNameUtil {
	
	private static final String[] URL_PREFIX = {"http://", "https://"};	
	private static final String DOMAIN_SEPARATOR = "/";
	
	public static String getUrlIp(String url){
		String domainName = null;
		for (String up : URL_PREFIX) {
			if(url.startsWith(up)){
				domainName = url.substring(up.length());
				domainName = domainName.substring(0, domainName.indexOf(DOMAIN_SEPARATOR));
				return getDomainIp(domainName);			
			}
		}
		return "";
	}
	
	public static String getDomainIp(String domainName) {
		try {
			InetAddress myServer = InetAddress.getByName(domainName);
			return myServer.getHostAddress();
		} catch (UnknownHostException e) {
		}
		return "";
	}

}

 2. Add IP parsing tools

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;

public class IpUtil {
	
	
	/**
     * Analyze hostIP from url<br/>
     * @param url
     * @author lh  
     * @return
     */  
    public static String getIpFromUrl(String url) {  
    	String host = "";  
    	// determine if it is empty  
        if (url == null || "".equals(url.trim())) {  
            return host;  
        }            
        Pattern p = Pattern.compile("(?<=//|)((\\w)+\\.)+\\w+");  
        Matches matches = p.matches (url);  
        if (matcher.find()) {  
            return matcher.group();  
        }
        return DomainNameUtil.getUrlIp(url);  
    }
	
	/**
	 * Get the IP of the requesting client (user IP)
	 * @param request
	 * @return
	 */
	public static String getRemortIP(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("X-Real-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		if (ip != null && ip.length() > 0) {
			String[] ipArray = ip.split(",");
			if (ipArray != null && ipArray.length > 1) {
				return ipArray [0];
			}
			return ip;
		}

		return "";
	}

}

 

3. Obtain the website IP corresponding to the http request

String url = StringUtils.isEmpty(request.getHeader("referer"))?request.getHeader("origin"):request.getHeader("referer");
String ipAddress = IpUtil.getIpFromUrl(url);
			

 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326196893&siteId=291194637