• Post Reply Bookmark Topic Watch Topic
  • New Topic

How to find a port is free or not without catching any Exception ?  RSS feed

 
venki sheshgiri
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Im making use of the below code snippet for finding whether a port is free or not

try {
InetSocketAddress addr = new InetSocketAddress(InetAddress.getByName("hostname"),1529); // initialization not shown
Socket s = new Socket();
s.connect(addr);
s.close();
} catch (IOException e) {
canConnect = false;
e.printStackTrace();
}

Is there way from which I can find out whether a port is free or not without getting any exception as in above code .
 
sunil sahoo
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Venki,
If you want to connect to any free port then just do the following.

Socket socket = new Socket("localhost",0);

In port, you have to insert as port number
 
venki sheshgiri
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sunil
The actual requirement is to find a list of free ports b/n a range say between 7000 to 9000 we will just find a port say 7002 which is free then incrementally use other ports which are free untill the range 9000 to host our services.
This has to work across all OS (HP ,IBM AIX,Sun Solaris,Windows)

didnt get "In port, you have to insert as port number" where I have to insert ?

Regards
Venki
 
sunil sahoo
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Venki,
I think you have first check for each operating system and then you have to run operating system specific commands to get the used ports
example
Below is the command to find out used ports for linux
netstat -tulnap
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!