mercredi 25 février 2015

How to get remote HTTP Port number in spring servlet?

I need to extract client's IP and port number when he makes a request to the servlet.


Here's my controller code:



@Controller
public class IpCheckerController {

String ip;
@ResponseBody
@RequestMapping(value = "/ipchecker", method = RequestMethod.GET)
public String get(HttpServletRequest request, HttpServletResponse response) throws IOException {
for (String header : HEADERS_TO_TRY) {
ip = request.getHeader(header);
if (ip != null && ip.length() != 0 && !"unknown".equalsIgnoreCase(ip)) {
return ip + "_"+request.getRemotePort(); // this port is wrong
// but I left it here for now.
}
}
return request.getRemoteAddr() + "_"+request.getRemotePort();
}

private static final String[] HEADERS_TO_TRY = {
"X-Forwarded-For",
"Proxy-Client-IP",
"WL-Proxy-Client-IP",
"HTTP_X_FORWARDED_FOR",
"HTTP_X_FORWARDED",
"HTTP_X_CLUSTER_CLIENT_IP",
"HTTP_CLIENT_IP",
"HTTP_FORWARDED_FOR",
"HTTP_FORWARDED",
"HTTP_VIA",
"REMOTE_ADDR" };


}


However it is not working as intended. At first I used getRemoteAddr() but it alays returns 127.0.0.1 or 0:0:0:0:0:0:0:1. Then I got this code from someone at work with checking for different headers and now it's working correctly.


However getRemotePort() returns wrong port. My application authentictes users based on ip and port I put into database on login. When someone makes and unauthorised attempt, logger writes down IP and port from which the attemps was made. This port is always different from what getRemotePort() shows.


What headers can I use to get the port just like with the IP? Is there a different way to extract port?


I can't use any extrernal services to parse this data, that's why I have to make my own servlet.


Aucun commentaire:

Enregistrer un commentaire