Home arrow static arrow Java Programming [Archive] - Negotiating a port number from the OS
Warning: Creating default object from empty value in /www/htdocs/w008deb8/wiki/components/com_staticxt/staticxt.php on line 51
Java Programming [Archive] - Negotiating a port number from the OS
This topic has 6 replies on 1 page.

Posts:929
Registered: 9/30/02
Negotiating a port number from the OS  
Aug 22, 2003 2:15 PM



 
All the socket classes require a port number to be specified. No problem, except as one of the requirements at work, I need to make a server that negotiates with the OS to receive a free port number. I can not hard code any numbers or receive them from the command line. I've looked through the forums and a few google searches, but I can't find anything useful. Does anyone here know how to do this or what technologies can do this? This requirement was kinda sprung on at the last minute, so even a simple hack may be exceptable. Thanks alot.

-JBoeing
 

Posts:11
Registered: 8/22/03
Re: Negotiating a port number from the OS  
Aug 22, 2003 2:26 PM (reply 1 of 6)



 
That's easy, bind the serversocket to port "0", it will do exactly what you want.
 

Posts:11
Registered: 8/22/03
Re: Negotiating a port number from the OS  
Aug 22, 2003 2:28 PM (reply 2 of 6)



 
That's easy, bind the serversocket to port "0", it
will do exactly what you want.

http://java.sun.com/j2se/1.4.1/docs/api/java/net/ServerSocket.html#ServerSocket(int)

see the first sentence:
Creates a server socket, bound to the specified port. A port of 0 creates a socket on any free port.

:-)

Regards Vaclav
 

Posts:929
Registered: 9/30/02
Re: Negotiating a port number from the OS  
Aug 22, 2003 3:02 PM (reply 3 of 6)



 
Thanks people. I overlooked that in the APIs.
 

Posts:2
Registered: 7/9/04
Re: Negotiating a port number from the OS  
Jul 30, 2004 6:29 AM (reply 4 of 6)



 
does that mean, i can do the following:

- create a ServerSocket on port 0
- ServerSocket is created on a free port
- I get the port number via myServerSocket.getLocalPort()
- I tell the client to connect on the now known port number

?
 

Posts:319
Registered: 11/8/00
Re: Negotiating a port number from the OS  
Jul 30, 2004 6:43 AM (reply 5 of 6)



 
yes but how will your client know the port number, it needs to connect to? Will you have to inform all the clients everytime the server starts.
 

Posts:2
Registered: 7/9/04
Re: Negotiating a port number from the OS  
Jul 30, 2004 6:53 AM (reply 6 of 6)



 
i have a parallel (non socket) communication channel open for message exchange ... so no problem about letting the client know about the port number
 
This topic has 6 replies on 1 page.