Monday, January 12, 2009

Get a free socket number

We have an integration test to test email sending which depends on green mail. When initialize green mail to mimic a mail server, we need specify the port number of the mail server. Before, we hard coded the port number. But when two build process are running at the same moment on the same build server, one process may not get the port because it was used by another.

To get a free socket number, using 0 as argument which creates a socket on any free port.
int freePort = new ServerSocket(0).getLocalPort();

Remember close the socket before you assign that port to green mail and start it, otherwise you will get error "port not available" because it was occupied already.

No comments:

Post a Comment