Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a UDP server in C?

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);
}
like image 636
Marco Manzoni Avatar asked May 25 '12 17:05

Marco Manzoni


2 Answers

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.

like image 131
cnicutar Avatar answered Nov 09 '22 03:11

cnicutar


No need to listen(2) on a UDP socket, as @cnicutar mentions, that is for TCP. Just recv(2) or recvfrom(2).

like image 37
Nikolai Fetissov Avatar answered Nov 09 '22 04:11

Nikolai Fetissov