« Tomcat Logging - Logging X-Forwarded-For in Tomcat 6 | Main | Apache Tomcat 5.5.27 Released »

09/09/2008

Java Code to Read the X-Forwarded-For Header

I am not a software developer...I'm a systems administrator.  That being said, I feel badly that by rolling out a BigIP LTM load-balancer I may have broken some web applications--specifically credit card applications that need to be able to look up the originating client IP address.

Sample code for a servlet to look up a client ip address might look something like this:

public void service(HttpServletRequest req, HttpServletResponse res) 
throws IOException {
String IP = req.getRemoteAddr();
}

The code that is broken by the BigIP is getRemoteAddr(). Typically, what this code does is grab the IP address from the HTTP environment variable "REMOTE_ADDR" but because the BigIP proxies requests, the only request you will see in the HTTP Header is the IP address of the unit that forwarded the request. The basic code below is intended to replace getRemoteAddr() with something that will pull the IP address out of X-Forwarded-For HTTP Header instead. Please note though that you are probably NOT going to want to use this code verbatim but it should serve as a trinket to get you started on some larger class that should look for the existence of X-Forwarded-For, handle errors, and also handle the possibility of handling multiple IPs in this header.  This can occur if your customers wind up passing through multiple proxies that support this header.

public void service(HttpServletRequest req, HttpServletResponse res) 
throws IOException {
String IP = req.getHeader("X-Forwarded-For");
}

Let me know how things go with this.

TrackBack

TrackBack URL for this entry:
https://www.typepad.com/services/trackback/6a01156fbc6fe6970c0115722881f2970b

Listed below are links to weblogs that reference Java Code to Read the X-Forwarded-For Header:

Comments