Uncategorized

Netstat and Java Socket Programming

In this article we are going to demonstrate netstat commands usage by creating a client and server open connection using Java socket programming.

Netstat

Netstat command is used to figure out how many Transport layer connections are created between systems. This information is useful to figure out the issues related to heavy usage of your application over network. Also to gauge which TCP connections are alive and perhaps problematic.

Server Code

Idea is to create a Server program which will always listens on port 4000 for connections.

import java.io.IOException;
import java.net.ServerSocket;

public class MySocketServer {

	public static int SERVER_PORT = 4000;

	public static void main(String args[]) throws IOException {
		ServerSocket server = new ServerSocket(SERVER_PORT, 1, null);
		System.out.println("Accepting Connections...");
		while(true) {
			server.accept();
			System.out.println("Connection accepted...");
		}
		
	}
}

Client code

Client makes a TCP socket connection with server on port 4000 and waits for 10 second.

import java.io.IOException;
import java.net.Socket;
import java.util.concurrent.CompletableFuture;

public class TCPConnectionTest {
	private static int errorCount = 0;
	public static void main(String args[]) throws Exception {
		CompletableFuture
		.runAsync(()->{
			try {
				testOpenSocket();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		});
		
		Thread.sleep(10000);
		System.out.println("Error count ::" + errorCount);
	}

	private static void testOpenSocket() throws IOException {
		Socket socket = null;
		try {
			socket = new Socket("localhost", MySocketServer.SERVER_PORT);
			System.out.println("Client Socket Created....");
		} catch (IOException e) {
			throw e;
		} 
	}

}

Output

Server Output Client Output
Connection accepted… Client Socket Created….
Error count ::0  

Netstat command output

Since client is waiting for 10 second. In mean time use netstat command to figure out that a TCP connection is created on localhost between port 4000 and 54708. (The port numbers are between 0 – 65535).

Conclusion

This command is a very useful tool to figure out network issues in your applications. As the foundation of all network intricacies in java is Socket programming which includes your application server.

One Commnet on “Netstat and Java Socket Programming

Leave a Reply

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