Hi,
I was wondering if there is anyway to determine programmatically whether a
port is available or whether its already in use before I do a bind() to that
port. Something akin to the macro INADDR_ANY - alhtough that gives the local
address (if I am not mistaken), what I am looking for is an easy way to get
a port number thats not already in use. Are there any macros or functions
that would let me do this?
|
|
0
|
|
|
|
Reply
|
Rookie
|
10/3/2004 11:34:54 AM |
|
"Rookie" <dominicjoseph@rediffmail.com> writes:
> Hi,
>
> I was wondering if there is anyway to determine programmatically whether a
> port is available or whether its already in use before I do a bind() to that
> port. Something akin to the macro INADDR_ANY - alhtough that gives the local
> address (if I am not mistaken), what I am looking for is an easy way to get
> a port number thats not already in use. Are there any macros or functions
> that would let me do this?
bind() to port 0, and the kernel will assign one for you. Use
getsockname() to find out which port you were given.
--
M�ns Rullg�rd
mru@mru.ath.cx
|
|
0
|
|
|
|
Reply
|
iso
|
10/3/2004 12:09:16 PM
|
|
In article <cjoo54$1lb$1@gist.usc.edu>,
"Rookie" <dominicjoseph@rediffmail.com> writes:
> Hi,
>
> I was wondering if there is anyway to determine programmatically whether a
> port is available or whether its already in use before I do a bind() to that
> port. Something akin to the macro INADDR_ANY - alhtough that gives the local
> address (if I am not mistaken), what I am looking for is an easy way to get
> a port number thats not already in use. Are there any macros or functions
> that would let me do this?
Even if there were, would it make sense? There'd be a window between when
you checked and when you bound to it, so something else could still get
there first, and the bind() could still fail.
As for picking a free local port, see inet(7p); you can either specify a
port number of zero, or not bind it at all before calling sendto() (UDP
only) or connect() (UDP or TCP), and let the system pick the port; unless
you want a privileged local port, in which case you have to either write
your own more complicated code to pick a port number, or use something
like rresvport(3socket) or rresvport_af(3socket) to pick the port number.
Most of the time, you probably don't want to bind the local address at
all; that lets the system pick the appropriate one in case there are
multiple interfaces.
--
mailto:rlhamil@smart.net http://www.smart.net/~rlhamil
Lasik/PRK theme music:
"In the Hall of the Mountain King", from "Peer Gynt"
|
|
0
|
|
|
|
Reply
|
Richard
|
10/3/2004 2:10:06 PM
|
|