tags:

views:

360

answers:

3

Is there any way by which i can find out free port on the server by executing a code from client computer.

Example for opening a port on my local machine:

ServerSocket localmachine = new ServerSocket(0);
int port = localmachine.getLocalPort();

This way I can retrieve a free port on my local machine.

Now suppose I have my own server: http://xyz.com

How can I get a free port for the server by running a program from client?

Basically I want to initiate a socket connection between client and a server. Which will be further used for communication purpose.

+3  A: 

The port information is only available to the server itself, so you'll need to run a program on the server to find a free port and send it to the client.

If you help us understand why you want to do this, we might be able to give a better answer.

Adam Davis
I am not trying to argue with you because I am definitely inexperienced in this...but why would it not be possible for a client to deduce an open port on a server? Isn't that the whole idea of a port-scan that people use to try and break in?
TheTXI
How will the program on the server return the port back to the client?
krisp
@TheTXI port scanning will tell you closed ports but just because the port is closed to you doesn't mean it is free.
stimms
@Stimms: Thank you for clearing that up.
TheTXI
@krisp - That's the point - there's no standard way of doing this. Make a program on the server that listens on port 8080, and whenever someone (a client) connects to 8080, the server finds a free port and sends the information to the client over port 8080.
Adam Davis
+1  A: 

Although I'm not sure what/why you will accomplish with this, you can just try to connect to the server with regular client sockets. If you do that in a loop you can probe all the ports. This may/may not tell you if the port is occupied, since there may be firewalls blocking certain ports. At least you can see if you see the port.

Tools like nmap will of course give you much more sophisticated analysis.

krosenvold
+1  A: 

A free port implies it is a port you can used. The only ports a client can use on a server are ports which are open on the server.

However, I assume you mean you want to find an unused port. This sounds like you are trying to do something which doesn't need to be done if you were to do whatever you are trying to a do a standard way.

However, to answer your question literally.

public static int unusedPort(String hostname) throws IOException {
    while (true) {
        int port = (int) (65536 * Math.random());
        try {
            Socket s = new Socket(hostname, port);
            s.close();
        } catch (ConnectException e) {
            return port;
        } catch (IOException e) {
            if (e.getMessage().contains("refused"))
                return port;
            throw e;
        }
    }
}
Peter Lawrey