1 import javax.servlet.http.HttpServletRequest; 2 3 /** 4 * 自定義訪問對象工具類 5 * 6 * 獲取對象的IP地址等信息 7 * @author X-rapido 8 * 9 */ 10 public class CusAccessObjectUtil { 11 12 /** 13 * 獲取用戶真實IP地址,不使用request.getRemoteAddr();的原因是有可能用戶使用了代理軟件方式避免真實IP地址, 14 * 16 * 可是,如果通過了多級反向代理的話,X-Forwarded-For的值並不止一個,而是一串IP值,究竟哪個才是真正的用戶端的真實IP呢? 17 * 答案是取X-Forwarded-For中第一個非unknown的有效IP字符串。 18 * 19 * 如:X-Forwarded-For:192.168.1.110, 192.168.1.120, 192.168.1.130, 20 * 192.168.1.100 21 * 22 * 用戶真實IP為: 192.168.1.110 23 * 24 * @param request 25 * @return 26 */ 27 public static String getIpAddress(HttpServletRequest request) { 28 String ip = request.getHeader("x-forwarded-for"); 29 if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { 30 ip = request.getHeader("Proxy-Client-IP"); 31 } 32 if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { 33 ip = request.getHeader("WL-Proxy-Client-IP"); 34 } 35 if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { 36 ip = request.getHeader("HTTP_CLIENT_IP"); 37 } 38 if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { 39 ip = request.getHeader("HTTP_X_FORWARDED_FOR"); 40 } 41 if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { 42 ip = request.getRemoteAddr(); 43 } 44 return ip; 45 } 46 47 }
/**
*獲取端口
*/
1 public void doGet(HttpServletRequest request, HttpServletResponse response) 2 throws ServletException, IOException { 3 String uri = request.getRequestURI();//返回請求行中的資源名稱 4 String url = request.getRequestURL().toString();//獲得客戶端發送請求的完整url 5 String ip = request.getRemoteAddr();//返回發出請求的IP地址 6 String params = request.getQueryString();//返回請求行中的參數部分 7 String host=request.getRemoteHost();//返回發出請求的客戶機的主機名 8 int port =request.getRemotePort();//返回發出請求的客戶機的端口號。 9 System.out.println(ip); 10 System.out.println(url); 11 System.out.println(uri); 12 System.out.println(params); 13 System.out.println(host); 14 System.out.println(port); 15 }