How to debug a Java socket connection

Summary: This article shares some source code for a Java socket debugging method.

I’ve been writing a lot of Java socket client code lately, and I found that when you're working with a Socket it’s nice to be able to print socket debug information. To that end, I wrote the following method that prints some basic debug information about a Java socket, and I thought I’d share this source code here.

Source code to debug a Java Socket

 * Prints debug output (to stdout) for the given Java Socket.
public void printSocketInformation(Socket socket)
    System.out.format("Port:                 %s\n",   socket.getPort());
    System.out.format("Canonical Host Name:  %s\n",   socket.getInetAddress().getCanonicalHostName());
    System.out.format("Host Address:         %s\n\n", socket.getInetAddress().getHostAddress());
    System.out.format("Local Address:        %s\n",   socket.getLocalAddress());
    System.out.format("Local Port:           %s\n",   socket.getLocalPort());
    System.out.format("Local Socket Address: %s\n\n", socket.getLocalSocketAddress());
    System.out.format("Receive Buffer Size:  %s\n",   socket.getReceiveBufferSize());
    System.out.format("Send Buffer Size:     %s\n\n", socket.getSendBufferSize());
    System.out.format("Keep-Alive:           %s\n",   socket.getKeepAlive());
    System.out.format("SO Timeout:           %s\n",   socket.getSoTimeout());
  catch (Exception e)

As you can see, this method takes a Java Socket as a parameter, and then calls several different methods on the socket to print out useful debug information.

Example Java socket debugging output

Here’s some example output from this socket debug method, showing the results when I create a socket that connects to Google on port 80:

Port:                 80
Canonical Host Name:
Host Address:

Local Address:        /
Local Port:           59558
Local Socket Address: /

Receive Buffer Size:  524660
Send Buffer Size:     131874

Keep-Alive:           false
SO Timeout:           0

There’s more debug information you can get about a socket, but I thought I’d share this example source code here to help you get started with debugging your socket connections. I hope it helps.