Why can't I connect to http server on localhost through a browser?

10,342

Solution 1

(I'm assuming you are using exactly the same URL in the browser and using curl ...)

If the browser is running on a different host to the service, then the reason is that localhost IP addresses (e.g. 127.0.0.1) are not routed to any other hosts apart from the host they were sent from. (That's what "local" means ...) In short, this is normal behaviour. (And maybe you are running curl and the browser on different hosts.)

If the browser is running on the same host as the service, this behaviour is a bit puzzling. However there are some possible explanations:

  • You may have some strange network proxy settings in your browser. For example, if you configure the browser to send ALL http requests (including 127.0.0.1) to an HTTP proxy on another machine, when the proxy relays the request to the real machine, it will go to the wrong place.

  • The localhost domain name may be bound to some strange IP address; e.g. something other than a 127.x.x.x IP address. (It is a strange thing to do, but I've heard of misguided people doing it.)

  • The 127.0.0.1 IP address might have been bound to something other that the loopback network adapter. (I don't know if this is technically possible ... )

  • If you are using iptables to implement routing on a virtual network, you could be sending 127.0.0.1 packets to the wrong place. (I don't know if this is technically possible ... )

The first bullet seems most likely to me.

Solution 2

Looks like port 6666 is considered unsafe by many browsers for security reasons. Please try some other ports may be port 3000 or 5000(I am just throwing a number here) it should work.

Share:
10,342
user1990198
Author by

user1990198

Updated on June 04, 2022

Comments

  • user1990198
    user1990198 almost 2 years

    I wrote a very simple Java http server for exercising purposes. I test it with cURL and everything seems to work fine but when I try to send a request from a browser

    http://localhost:6666/
    

    the server does not respond. I even put a marking System.out.println() at the point when the server socket accepts a connection which doesn't seem to fire when i try to hit the server through a browser. Please help me out with this. Thanks :)

    EDIT: Part of the code:

    public class Server {
    
        private ServerSocket serverSocket;
        private Socket socket;
        public Server() {
            try {
                serverSocket = new ServerSocket(6666);
                while (true) {
                    socket = serverSocket.accept();
                    System.out.println("Whoop! Connection!");
                    Request request = new Request(socket);
                    request.run();
                }
            } catch (IOException e) {
                e.printStackTrace();
              }
        }
    }
    

    Where Request is a class which extends Thread in order to handle multiple requests