• Post Reply Bookmark Topic Watch Topic
  • New Topic

how to find out available ports  RSS feed

 
ajse ruku
Ranch Hand
Posts: 196
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all,
I want to find out the number of available ports through java.How can I do this?

with regards,
ajse
 
Martin Simons
Ranch Hand
Posts: 196
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Try binding to them. Really there is no API call for this, and there should not be. Besides, attempting to bind a socket to an IP/Port combination takes about 1 millisecond, so choose a range of ports attempt to bind to them. But remember, with this method, and any hypothetical "free ports" method, just because a port is "free" this millisecond, does not mean it will be free in the next millisecond (this is especially true for ports above 20,000).
 
Shakeel Kadam
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sample Source Code:

Like what was earlier said, I port is free now does not mean that it will be free later. A port is blocked now does not mean that it will not be free later.

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

public class Test {

public static final String NEWLINE = System.getProperty( "line.separator" );

public void tryToConnect(InetAddress address, int port ) {

try
{
Socket socket = new Socket( address, port );
socket.close();

System.out.println( "Connected successfully to " + address + " : " + port );
}
catch ( Exception ex )
{

System.out.println( "Error attempting to connect to " + address + " : " + port + " with exception : " + ex.getMessage() );
}

}


public void tryToConnect(String host, int port ) {

try
{

InetAddress address = InetAddress.getByName( host );
Socket socket = new Socket( address, port );
socket.close();

System.out.println( "Connected successfully to " + host + " : " + port );
}
catch ( Exception ex )
{

System.out.println( "Error attempting to connect to " + host + " : " + port + " with exception : " + ex.getMessage() );
}

}

public static void main( String[] args ) throws Exception {

System.out.println( "Starting the test" );

Test test = new Test();

test.tryToConnect( "localhost", 80 );

System.out.println( "Done with the test" );
}
}
 
Mathias Nilsson
Ranch Hand
Posts: 367
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Another sample

 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!