A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.tutorialspoint.com/javaexamples/net_port.htm below:

How to check whether a port is being used or not in Java

How to check whether a port is being used or not in Java Problem Description

How to check whether a port is being used or not?

Solution

Following example shows how to check whether any port is being used as a server or not by creating a socket object.

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

public class Main {
   public static void main(String[] args) {
      Socket Skt;
      String host = "localhost";
      
      if (args.length > 0) {
         host = args[0];
      }
      for (int i = 0; i < 1024; i++) {
         try {
            System.out.println("Looking for "+ i);
            Skt = new Socket(host, i);
            System.out.println("There is a server on port " + i + " of " + host);
         } catch (UnknownHostException e) {
            System.out.println("Exception occured"+ e);
            break;
         } catch (IOException e) {}
      }
   }
}
Result

The above code sample will produce the following result.

Looking for 0
Looking for 1
Looking for 2
Looking for 3
Looking for 4. . . 

java_networking.htm


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4