Yes, that's correct and a better approach than trial and error.
When assigning port 0 to a socket, it means it will get a random port right?
Use the getsockname function to retrieve the local address for a socket.
Now I want to know what port the OS assigned to my socket.
Of course, the typical server accepts multiple connections on the one listening port, so I assume you have a good reason for using a multiple port solution. FTP uses a multiple port solution and it causes a lot of problems. With this model, you will have to inform the client of which port to use.
#pragma comment(lib, "ws2_32.lib")
struct sockaddr_in addr;
struct sockaddr_in actual_address;
int addr_size = sizeof(actual_address);
WSAStartup(MAKEWORD(2, 2), &wsad);
sock = socket(AF_INET, SOCK_STREAM, IPPROTO_IP);
addr.sin_family = AF_INET;
addr.sin_port = htons(0);
addr.sin_addr.S_un.S_addr = INADDR_ANY;
bind(sock, (struct sockaddr*) &addr, sizeof(addr));
getsockname(sock, (struct sockaddr*) &actual_address, &addr_size);
printf("The selected port is %d.\n", ntohs(actual_address.sin_port));