Page 1 of 1

Get free TCP port?

Posted: Mon Sep 15, 2008 9:36 pm
by junkoi
Hi,

I want to start my daemon at a particular TCP port. The exact port number is not important, so what matters is having a free port that is not in use by other daemons. And it is better to have a port out of range [0, 1024] that is dedicated for "system" ports.

So is there a good way to find a free port for my purpose? Of course we can always enumerating the port (for ex by using "netstat -t"), so we can see which one is not in use. But I dont like that way very much.

The programming language is C, in Linux. Any idea?

Many thanks,
J

Re: Get free TCP port?

Posted: Tue Sep 16, 2008 1:29 am
by pcmattman
Try opening a socket on each TCP port (for loop) to listen on. If it's already in use you'll not be able to open the socket and get an error code.

Of course, this could succeed (or fail) at the wrong time and give you incorrect information, but it's a nice hacky way of solving the problem :D

Re: Get free TCP port?

Posted: Tue Sep 16, 2008 2:38 am
by Solar
First, check out /etc/services, and chose one of the numbers not already taken by "well known" services. Then check Google to find out about not-so-well-known services that might use that port.

Then, make that port number the default in your config file, and leave it to the admin / user to find another if the default is already taken.

IMHO, you should not trial-and-error through port numbers. A service should have a default port number, always, if only because it makes it easier for clients to find your service. And imagine several services at once trial-and-error'ing through the port range, colliding, flooding the error logs, and generally making a mess of things...