NanoHttpd is only one source file: here's a relevant clip:
/**
* Constructs an HTTP server on given hostname andport.
*/
public NanoHTTPD(String hostname, int port) {
this.hostname = hostname;
this.myPort = port;
setTempFileManagerFactory(new DefaultTempFileManagerFactory());
setAsyncRunner(new DefaultAsyncRunner());
}
/**
* Start the server.
* @throws IOException if the socket is in use.
*/
public void start() throws IOException {
myServerSocket = new ServerSocket();
myServerSocket.bind((hostname != null) ? new InetSocketAddress(hostname, myPort) : new InetSocketAddress(myPort));
While I'm not in a position to try it from here, it seems like you could achieve the effect you want by constructing your server with new NanoHTTPD("localhost",8080)
-- as that would cause the bind operation to bind to the port on localhost (instead of using the wildcard bind)
UPDATE: Since it appears people are still reading -- and occasionally upvoting :^) -- my off-the-cuff answer years later, I thought I would add this caveat: if you are binding only to localhost for security reasons (i.e. you "trust" things running on localhost, but you want to block connections from the big bad Internet,) keep in mind binding to localhost only means the tcp connection to NanoHttpd must have a local source address -- but it is still possible that a "local" connection could be initiated by a remote bad actor, using some other software on your host as a springboard. For example, a misconfigured http proxy running on the same host might get tricked into connecting to 'http://localhost:8080' on behalf of a remote user. Restricting connect access to the local host is helpful, of course, but consider the context: if you are protecting a high-value resource -- and especially if you have other public-facing services on the same host that might be compromised -- binding to localhost is no substitute for using proper cryptographic authentication.