Is “Connection refused” always a network issue?

We are trained to think that if we see “java.net.ConnectException: Connection refused”, we need to talk to our friends in networking.

However, below is at least one example where this is not the case.

Create a very simple socket server with the following…

import java.io.*;
import java.net.*;

public class myServer {

  public static void main(String[] args) throws IOException {
    ServerSocket listener = new ServerSocket(9999);
    try {
      while (true) {
        Socket socket = listener.accept();
        PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
        out.println("foo");
      }
    }
    finally {
      listener.close();
    }
  }
}

We create another class name myClient, as shown below…

import java.io.*;
import java.net.*;

public class myClient {
  public static void main(String[] args) throws IOException {
    for (int i = 1; i <= 50; i++) {
      Socket s = new Socket("our_server_host", 9999);
      BufferedReader input =  new BufferedReader(new InputStreamReader(s.getInputStream()));
      System.out.println(input.readLine());
    }
  }
}

The trick to making our test work (or fail, in this case), is to set our open file limit very low in the shell in which we will run our myServer class. In linux, simply type:

ulimit -n 20

We then start our server in this shell with the following:

java myServer

This limits our open files, with which sockets are included, to 20.

We then open another shell, in which we will run our myClient class. We need another shell to ensure our test driver is not subject to the same file limit as we artificially imposed above.

When we run our myClient class, we quickly see the following:

-sh-4.1$ java myClient
Exception in thread "main" java.net.ConnectException: Connection refused
        at java.net.PlainSocketImpl.socketConnect(Native Method)
        at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:351)
        at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:213)
        at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:200)
        at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:366)
        at java.net.Socket.connect(Socket.java:529)
        at java.net.Socket.connect(Socket.java:478)
        at java.net.Socket.(Socket.java:375)
        at java.net.Socket.(Socket.java:189)
        at myClient.main(myClient.java:7)
-sh-4.1$ 

The moral of the story is check your process limits, at a minimum, before you go after the network guys. It could still be a firewall issue, but if it is very hit or miss, it probably isn't a firewall issue. It may just mean the remote server process cannot respond to your request, for whatever reason.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.