Skip to content
Advertisement

How to configure com.sun.net.httpserver to accept only requests from localhost?

I am using the com.sun.net.httpserver.HttpServer to handle some http requests. My http server runs behind nginx that maps the server domain names and forward the requests to my server by using it as a proxy running at a certain port. My http server takes all requests if they access the port where the server is running. I want a mechnism so that the server accept only requests from a domain that is supposed to be available, the same I use with nginx. I guess it would help if I could force the http server to be accessable by localhost only.

What would be the best way to achieve that?

Advertisement

Answer

I guess it would help if I could force the http server to be accessable by localhost only.

A Java SE HttpServer instance1 listens for requests on the IP address that it is bound to2. So bind it to a loopback IP address like this:

InetAddress localHost = InetAddress.getLoopbackAddress();
InetSocketAddress sockAddr = new InetSocketAddress(localHost, 80);
HttpServer server = HttpServer.create(sockAddr, 0);

More generally, if you only want to accept requests from a given set of IP addresses, one approach would be to call HttpExchange::getRemoteAddress in your handler and act appropriately if the remote address is not what you want. But beware that the remote address is going to be the immediate upstream IP address. It could be your reverse proxy, or some forward proxy used by the remote user.

But if you are looking for something where you can accept all request but only respond to requests that are addressed to a specific domain names (as per a conventional vhosts file) I think you are going to have to implement that filtering yourself. HttpServer is designed to be a simple light-weight server … not a full functionality web container.


1 – This only applies to the HTTPServer classes provided by the JDK. For others, YMMV.
2 – Unless you bind to the wild-card address …

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement