Mailing Lists: Apple Mailing Lists

Image of Mac OS face in stamp
 
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: detecting whether a port is in use



At 4:38 +0000 30/10/06, Martin Redington wrote:
Is there any easy way to detect if a port is already being used,
before attempting to bind to it ...

This sounds like a bad idea to me, because it automatically introduces a race condition between the time you check that the port is available and the time that you bind. Given that this race exists, you bind code has to handle "port is use" errors cleanly. And, given that, you might as well not both checking in advance.


Still, I assume you've thought about this, so I'll answer your direct question. No, there is no direct method for doing this. While I can hardly claim to be an authority on sockets, my guess is that the folks who designed the API didn't include such a method because of the above-mentioned race condition.

There are, however, numerous indirect methods to do it, but none of them are ideal. You could, for example, attempt to connect (or, for UDP, send to) the port and look at the error you get back. Alternatively, you could list the open ports and search that list. Techniques for doing this were covered in the recent thread on this mailing list entitled "how to enumerate TCP and UDP listeners".

S+E
--
Quinn "The Eskimo!"                    <http://www.apple.com/developer/>
Apple Developer Relations, Developer Technical Support, Core OS/Hardware
_______________________________________________
Do not post admin requests to the list. They will be ignored.
Macnetworkprog mailing list      (email@hidden)
Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/macnetworkprog/email@hidden

This email sent to email@hidden
References: 
 >detecting whether a port is in use (From: "Martin Redington" <email@hidden>)



Visit the Apple Store online or at retail locations.
1-800-MY-APPLE

Contact Apple | Terms of Use | Privacy Policy

Copyright © 2007 Apple Inc. All rights reserved.