`

webservice和HttpServletRequest两种方式获取客户端ip的方法

 
阅读更多

1、HttpServletRequest获取客户端IP方法:

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
 * 
 * <p>Title: [HttpServletRequest获取客户端IP方法类] </p>
 * <p>Description: [HttpServletRequest获取客户端IP方法]</p>
 * <p>Copyright: Copyright (c) 2013</p>
 * @update [修改人] [修改时间]
 * @version $Revision$
 */
public class CheckMACandIP extends HttpServlet {
	
	private static final long serialVersionUID = 1L;
	public CheckMACandIP() {
	  super();
	 }
	 public void destroy() {
	  super.destroy(); 
	 }
	 public void doGet(HttpServletRequest request, HttpServletResponse response)
	   throws ServletException, IOException {
	  doPost(request,response);
	 }

	 public void doPost(HttpServletRequest request, HttpServletResponse response)
	   throws ServletException, IOException {
	  String ip = getRemoteAddress(request);
	  System.out.println(ip);
	 }
	 
	 public void init() throws ServletException {
	 }
	 /**
	  * 
	  * <p>Discription:HttpServletRequest获取客户端IP方法</p>
	  * @param request
	  * @return
	  * @update [修改人] [修改时间] [变更描述]
	  */
	 public String getRemoteAddress(HttpServletRequest request){    
	     String ip = request.getHeader("x-forwarded-for");    
	     if(ip == null || ip.length() == 0 || ip.equalsIgnoreCase("unknown")) ip = request.getHeader("Proxy-Client-IP"); 
	     System.out.println(ip);
	     if(ip == null || ip.length() == 0 || ip.equalsIgnoreCase("unknown")) ip = request.getHeader("WL-Proxy-Client-IP");
	     System.out.println(ip);
	     if(ip == null || ip.length() == 0 || ip.equalsIgnoreCase("unknown")) ip = request.getRemoteAddr();
	     System.out.println(ip);
	     return ip;    
	 }
}

 2、webservice方式获取客户端ip的方法:

import org.apache.axis.MessageContext;
import javax.servlet.http.HttpServletRequest;
import org.apache.axis.transport.http.HTTPConstants;

/**
	 * 
	 * <p>Discription:动态获取前置机代理健康档案IP地址</p>
	 * @return
	 * @update [修改人] [修改时间] [变更描述]
	 */
	public static String getClientIpAxis() {
		MessageContext mc = null;
		HttpServletRequest request = null;
		try {
			mc = MessageContext.getCurrentContext();
			if (mc == null)
				throw new Exception("无法获取到MessageContext");
			request = (HttpServletRequest) mc
					.getProperty(HTTPConstants.MC_HTTP_SERVLETREQUEST);
			log.info("前置机ip地址:" + request.getRemoteAddr());
		} catch (Exception e) {
			System.out.println(e.getMessage());
			e.printStackTrace();
		}
		return request.getRemoteAddr();
	}

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics