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
Get free TCP port?
-
- 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?
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
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
Re: Get free TCP port?
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...
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.