Get free TCP port?

Programming, for all ages and all languages.
Post Reply
junkoi
Member
Member
Posts: 63
Joined: Wed Jan 23, 2008 8:55 pm

Get free TCP port?

Post 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
pcmattman
Member
Member
Posts: 2566
Joined: Sun Jan 14, 2007 9:15 pm
Libera.chat IRC: miselin
Location: Sydney, Australia (I come from a land down under!)
Contact:

Re: Get free TCP port?

Post 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
User avatar
Solar
Member
Member
Posts: 7615
Joined: Thu Nov 16, 2006 12:01 pm
Location: Germany
Contact:

Re: Get free TCP port?

Post 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...
Every good solution is obvious once you've found it.
Post Reply