How to create a UDP server in C?

Marco Manzoni picture Marco Manzoni · May 25, 2012 · Viewed 14.9k times · Source

I'm trying to write a UDP server in C (under Linux). I know that in the socket() function I must use SOCK_DGRAM and not SOCK_STREAM.

if ( (list_s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0 ) 
{
    fprintf(stderr, "ERROR");
}

But now, when I try to run the program (no errors in compiling), it says that there is an error in listen(). Here is the call to it:

if (listen(list_s, 5) < 0)
{
    fprintf(stderr, "ERROR IN LISTEN");
    exit(EXIT_FAILURE);
}

Can you figure out what the problem is? This is the code:

int       list_s;                /*  listening socket          */
int       conn_s;                /*  connection socket         */
short int port;                  /*  port number               */
struct    sockaddr_in servaddr;  /*  socket address structure  */

if ( (list_s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0 ) 
{
    fprintf(stderr, "ERROR\n");
}

memset(&servaddr, 0, sizeof(servaddr));
servaddr.sin_family      = AF_INET;
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
servaddr.sin_port        = htons(port);

if ( bind(list_s, (struct sockaddr *) &servaddr, sizeof(servaddr)) < 0 )
{
    fprintf(stderr, "ERROR IN BIND \n");
}

if ( listen(list_s, 5) < 0 )      // AL POSTO DI 5 LISTENQ
{
    fprintf(stderr, "ERROR IN LISTEN\n");
    exit(EXIT_FAILURE);
}

Answer

cnicutar picture cnicutar · May 25, 2012

You can't listen on a datagram socket, it's simply not defined for it. You only need to bind and start reading in a loop.

As a short explanation, listen informs the OS that it should expect connections on that socket, and that you're going to accept them at a later time. Obviously that doesn't make sense for datagram sockets, thus the error.


Side note: you should try to use perror to print such errors. In this case it would (likely) have said Operation not supported.