Search code examples
javahttpserveripv4

Create HttpServer with public ipv4 address


I'm setting up a HttpServer via com.sun.net.httpserver. I want to be able to reach the server via my public ipv4 address.

I already managed to get it working with localhost.

HttpServer server = HttpServer.create(new InetSocketAddress(8080), 0);
server.createContext("/", Main::server.setExecutor(null);
server.start();

I tried it with

InetAddress ip = InetAddress.getByName("83.180.65.342");
HttpServer server = HttpServer.create(new InetSocketAddress(ip, 8080), 0);

But it returns

java.ne.BindException: Cannot assign requested address: bind

Solution

  • Are you doing this on a local development machine while your public machine is actually a distinct machine elsewhere ? That obviously won't work.

    If that is the problem, make your IP address a configurable property in the installation instead of hardcoding it. Or else use getLocalHost() (and configure your machines' networking and DNS options properly so that it won't return 127.0.0.1).