Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C / how to listen on multiple UDP ports

Tags:

c

sockets

The application I am working on should be able to listen to multiple (right now 4) port numbers. Do I need to create a socket for every of these ports, like:

if((sock_fd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
    perror("error: could not create UDP socket\n");
    exit(EXIT_FAILURE);
}

bzero(&sock_addr, sizeof(sock_addr));
sock_addr.sin_family    = AF_INET;
sock_addr.sin_port      = htons(port1);
sock_addr.sin_addr.s_addr   = inet_addr(INADDR_ANY);

if(bind(sock_fd, (struct sockaddr *) &sock_addr, sock_len) < 0) {
    perror("error: could not bind UDP socket to AU\n");
    exit(EXIT_FAILURE);
}

Or is there a more elegant way to do that? Also I read about the select() statement, would that be something I should use? The reason I want to listen on several ports is quite simple, it should identify the application I am communicating with. E.g. one application per port.

Thanks in advance for your comments.

// UPDATE: How should I set up the one socket per port?

like image 957
nyyrikki Avatar asked Oct 29 '25 18:10

nyyrikki


1 Answers

Yes, you need separate sockets for each pair of (IP,port) numbers that you wish to communicate through.

And yes, you can absolutely use the select() function (it's not a "statement" which implies being somehow part of the language, it's just a function in the library) to service the multiple sockets once you've set them all up.

like image 166
unwind Avatar answered Oct 31 '25 07:10

unwind