取得请求地址对应的网站IP

阅读更多

1、添加域名解析工具类

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

/**
 * 域名解析工具类
 * @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、添加IP解析工具类

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

import javax.servlet.http.HttpServletRequest;

public class IpUtil {
	
	
	/** 
     * 从url中分析出hostIP
* @param url * @author lh * @return */ public static String getIpFromUrl(String url) { String host = ""; // 判断是否为空 if (url == null || "".equals(url.trim())) { return host; } Pattern p = Pattern.compile("(?<=//|)((\\w)+\\.)+\\w+"); Matcher matcher = p.matcher(url); if (matcher.find()) { return matcher.group(); } return DomainNameUtil.getUrlIp(url); } /** * 取得请求客户端的IP(用户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、取得http请求对应的网站IP

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

 

 

你可能感兴趣的:(java,ip)