Home > OS >  Can 2 process receive UDP package from the same port?
Can 2 process receive UDP package from the same port?

Time:08-08

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?

CodePudding user response:

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.

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);
}   

There is also possibility that two process shares the same UDP socket after fork(). That way two separate process can share the same port number at the same time. But that approach is rarely used, and behavior is different.

  • Related