Click to See Complete Forum and Search --> : Is there any method to get a free port number to listen on the local machine
Speed
January 4th, 2003, 10:36 AM
I'm going to write a FTP server. It should always listening on any random
port if free for PASV mode. Is there any method to get one free port number
to listen on?
I've thought of a silly-method like that:
short GetFreePortToListen()
{
sockaddr_in sin;
short port = 2000;
sin.sin_family = AF_INET;
SOCKET s;
s = socket(AF_INET, SOCK_STREAM, 0);
ASSERT(s!=INVALID_SOCKET);
while (true) {
sin.sin_port = ntohs(port);
if (bind(s, (SOCKADDR*)&sin, sizeof(sockaddr_in))==0) {
shutdown(s);
return port;
}
port++;
}
}
I know, it's so silly!
Is there any right / good way ??
TheCPUWizard
January 4th, 2003, 10:47 AM
There may be more consise references available but the MSDN Link (http://msdn.microsoft.com/library/default.asp?url=/library/en-us/iisref60/htm/ref_mb_passiveportrange.asp) provides a good starting point for information about PASV. [Much of the information is IIS specific]
The port is not really random. See the referenced material and some of the links availabe from there to start.
Hope this helps.
Speed
January 4th, 2003, 11:32 AM
Thanks very much!
DanM
January 4th, 2003, 01:18 PM
1) You will automatically get a random port when specifying the port number as 0. The documentation says:
For TCP/IP, if the port is specified as 0, the service provider assigns a unique port to the application with a value between 1024 and 5000.
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/wcewinsk/htm/_wcesdk_bind.asp
2) Your method is not good because there may be another application doing a bind on the same port you choose right after you call shutdown(s) - doing a bind, shutdown and a bind again is not an atomic operation and I don't think there is any way to enforce it to be atomic
3)You also have a handle leak because you you are missing a closecocket call.
The shutdown function does not close the socket. Any resources attached to the socket will not be freed until closesocket is invoked.
Dan
DanM
January 4th, 2003, 01:19 PM
It was supposed to be closesocket, sorry :)
Dan
Speed
January 4th, 2003, 09:14 PM
Thanks to Dan.
You've exactly solved my question.
DanM
January 4th, 2003, 11:44 PM
Cool :)
Dan
codeguru.com
Copyright WebMediaBrands Inc., All Rights Reserved.