[ale] Open port

Joseph A Knapka jknapka at earthlink.net
Thu May 23 00:51:51 EDT 2002


Joseph A Knapka wrote:
> 
> Jeff Tillotson wrote:
> >
> > In C, is there a way to check if a port is open prior to opening it?   I have
> > lookef at getsockopt but that won't so what I want.  I have search the web
> > and "UNIX Networking Programming" and there isn't an answer there.
> >
> > What I need is to check if a port is already open.  If it is open then I just
> > exit the app.  If it isn't then I will bind to the port and all is good.
> >
> > Any assistance would be appreciated.
> 
> Try to connect() to it at the IP address you intend
> to bind it at. If you get ECONNREFUSED, then it's
> probably open. Unless IPchains or similar is in the
> way.

Silly me.

This is the Wrong Answer - there's a huge
race condition, and that race condition would be
present in any scenario that involved chacking for
the open port, and then doing the bind - some other
process could bind the socket in between. The right
thing to do is to call bind() and be prepared to
deal with failure - in other words, do whatever it
is you were planning to do if the port were already
bound.
 
Cheers,

-- Joe
   Looking for a new .sig.

---
This message has been sent through the ALE general discussion list.
See http://www.ale.org/mailing-lists.shtml for more info. Problems should be 
sent to listmaster at ale dot org.






More information about the Ale mailing list