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)
Not so, see below.
Sure, you could just not
bindor passNULLasport. 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 of0the kernel chooses an ephemeral port when bind is called.Here’s a quote from TLPI:
Back to your questions:
Not necessarily. They don’t “get mixed up”.