How to create a UDP server in C?

2019-06-16 03:52发布

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

2条回答
男人必须洒脱
2楼-- · 2019-06-16 04:32

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

查看更多
萌系小妹纸
3楼-- · 2019-06-16 04:34

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.

查看更多
登录 后发表回答