BSD - use any port available?
All of the tutorials and examples I find online always specify a port number like 7000 or 4950 etc. What if those ports are open on one computer, but another? Seems like that case makes doing that a bad idea. Is there a way to say "find and use any open port"? My code now is like this -
//get server info, put into servinfo
if ((status = getaddrinfo("192.168.2.2", port, &hints, &servinfo)) != 0) {
fprintf(stderr, "getaddrinfo error: %s\n", gai_strerror(status));
return false;
}
with port being 4950. This is for a tcp socket, but I'm assuming it will be the same general strategy for udp?
Also quick question - if I am using both tcp and udp connections in an application, should they use different ports? (didn't feel like this deserved another question)开发者_如何学C
Seems like that case makes doing that a bad idea
Not so, see below.
Is there a way to say "find and use any open port"?
Sure, you could just not bind
or pass NULL
as port
. But then, how would the clients know where to connect to ? You would have to publish this information somewhere.
Back to bind(2)
. If you specify a port of 0
the kernel chooses an ephemeral port when bind is called.
Here's a quote from TLPI:
There are other possibilities than binding a server’s socket to a well-known address. For example, for an Internet domain socket, the server could omit the call to bind() and simply call listen(), which causes the kernel to choose an ephem- eral port for that socket.
Afterward, the server can use
getsockname()
to retrieve the address of its socket. In this scenario, the server must then publish that address so that clients know how to locate the server’s socket. Such publication could be done by registering the server’s address with a centralized directory service application that clients then contact in order to obtain the address.
Back to your questions:
Also quick question - if I am using both tcp and udp connections in an application, should they use different ports
Not necessarily. They don't "get mixed up".
精彩评论