Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check domain or IP that request came from? [duplicate]

Tags:

servlets

I have a servlet, is it possible to check if a request came from a specific domain, say "example.com"?

public abstract class MyServlet extends HttpServlet {

public void doPost(HttpServletRequest req, HttpServletResponse resp) 
    throws ServletException, IOException 
{
        if (didOriginateFrom("example.com", req)) {
            // ok to process
        }
    }
}

I have one server that will offload some work to a secondary server (above), just want to make sure it only process requests that come from my primary server,

Thanks

like image 878
user291701 Avatar asked Oct 08 '22 05:10

user291701


1 Answers

The below methods give you the information of the client host machine which has made the request.

  • HttpServletRequest.getRemoteAddr()
  • HttpServletRequest.getRemoteHost()

Here is the code you are looking for:

boolean didOriginateFrom(Sting host, HttpServletRequest req) {
   return req.getRemoteHost().contains(host);
} 

Both the above methods gives information about the client or the last proxy address that sent the request.

Some servers might return the original client address though the request has come through several proxies. Proxies send the address of the immediate client to the server by adding X-Forwarded-For header. Thus some servers might process the X-Forwarded-For header values and return the original client address.

Here is how the X-Forwarded-For request header might look

X-Forwarded-For : originalclient, proxy1, proxy2, lastproxy
like image 66
Ramesh PVK Avatar answered Oct 12 '22 11:10

Ramesh PVK