0

I've been given a practical where I have to create a socket connection to the localhost of the machine and to test the connection for port numbers 1 to 65535.

Here's what I've done so far

Socket sConnection = null;
    try {
        sConnection = new Socket("localhost",4);
        System.out.println("Connected to " + sConnection.getInetAddress());
    }catch(UnknownHostException ex) {
        ex.printStackTrace();
    }catch(IOException ex) {
        ex.printStackTrace();
    }
    finally {
        try {
            if(sConnection != null) {sConnection.close();}
        }catch(IOException ex) {
            ex.printStackTrace();
        }
    }
}

Now the problem is i keep getting a connection Exception

java.net.ConnectException: Connection refused: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:79)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
at java.net.Socket.connect(Socket.java:589)
at java.net.Socket.connect(Socket.java:538)
at java.net.Socket.<init>(Socket.java:434)
at java.net.Socket.<init>(Socket.java:211)
at Main.main(Main.java:9)

I've disabled my antivirus and firewall, I've checked all available ports and selected a few that are listening and open but still getting the same error.

Stephen C
  • 632,615
  • 86
  • 730
  • 1,096
  • 'Connection refused' means nothing was listening at the IP:port you tried to connect to. TCP port 4 is unassigned in RFC 1700. – user207421 Jul 25 '20 at 11:37

1 Answers1

0

"Connection refused" means there is nothing listening on the port you try to connect to. When you are scanning ports 1 to 65535, this is expected to happen with most ports. It's a sign that you should move on to the next port.

To illustrate:

for (int port = 1; port < 65535; port++) {
    try {
        ... try connecting to port ...
    } catch (java.net.ConnectException ex) {
        System.out.println("Nothing on port " + port);
    }
    ... handle other errors ...
}
Joni
  • 101,441
  • 12
  • 123
  • 178