Check domain or IP address from which the request comes from?

I have a servlet, can I 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 upload some work to the secondary server (see above), I just want to make sure that it only processes requests coming from my main server,

thanks

+4
source share
2 answers

The following is information about the host computer of the client who 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 of these methods provide information about the client or the last proxy address that sent the request.

Some servers may return the source address of the client, although the request went through several proxies. Proxies send the address of the immediate client to the server, adding an X-Forwarded-For header. Thus, some servers can process the X-Forwarded-For header values ​​and return the original client address.

Here's what the X-Forwarded-For request header looks like

 X-Forwarded-For : originalclient, proxy1, proxy2, lastproxy 
+3
source

If I understand correctly, javax.servlet.ServletRequest.getServerName() should work. It also provides additional methods for retrieving request information, getScheme (), getServerPort () ...

0
source

All Articles