Reputation: 127
I am writing a client program receiving data from a UDP server.
The client send a subscribe request to specified (ip, port) of server, and the server start sending UDP package to specified port of client. If some package is missing, the client send a request to another server requesting that package.
My questions, after I compile and run the client program, can I start another instance of the same client program?
Upvotes: 1
Views: 1794
Reputation: 8466
You can run several instances of the same client program.
But, You can't bind the same UDP port number for 2 different UDP socket at the same time in a host (without SO_REUSEADDR).
So those client instances should use different client UDP port numbers. The best way to get different port numbers for clients: Let the OS allocate free port numbers for client sockets.
Usually that can be done by using port number zero, when binding the socket:
struct sockaddr_in addr;
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = INADDR_ANY;
addr.sin_port = 0;
if (bind(sockfd, (const struct sockaddr *)&addr, sizeof(addr)) == -1)
{
perror("bind failed");
exit(EXIT_FAILURE);
}
edit:
For receiving UDP broadcast, you can use socket option SO_REUSEADDR
between socket()
and bind()
calls:
int val = 1;
if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &val, sizeof(val)) == -1)
{
perror("setsockopt failed");
exit(EXIT_FAILURE);
}
struct sockaddr_in addr;
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = INADDR_ANY;
addr.sin_port = htons(12345);
if (bind(sockfd, (const struct sockaddr *)&addr, sizeof(addr)) == -1)
{
perror("bind failed");
exit(EXIT_FAILURE);
}
That way several processes can bind the same port for receiving broadcast messages. --> A broadcast message will be delivered to all 'listeners'.
Upvotes: 2