adelbertc
adelbertc

Reputation: 7320

C UDP socket not working

I'm having a problem with one of my homework assignments on socket programming in C.. we're doing a simple client/server thing with UDP and I'm having trouble with the server.. here's a snippet:

int main(int argc, char *argv[])
{
    int sockfd, newsockfd, portno;
    socklen_t clilen;
    char buffer[PACKET_DATA_LENGTH];
    struct sockaddr_in serv_addr, cli_addr;
    int n;
    if (argc < 2) {
        fprintf(stderr,"ERROR, no port provided\n");
        exit(1);
    }
    sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (sockfd < 0)
        error("ERROR opening socket");

Originally the sockfd = socket(AF_NET, SOCK_DGRAM, 0) was a SOCK_STREAM, but since the project specification was to do it in UDP and not TCP I changed STREAM to DGRAM.

I call the server like: ./receiver 1234

And I get the error: ERROR on accept: Operation not supported on socket

However, if I change it back from DGRAM to STREAM it compiles and ./receiver 1234 works fine.

Help?

Thanks! -kstruct

EDIT This is what error() looks like (this is pre-given code, I did not write it, it came as part of the project)

void error(const char *msg)
{
    perror(msg);
    exit(1);
}

EDIT2 Here's more of my code (what follows immediately after the first block of code I posted).. I guess the boilerplate code does call accept(), but shouldn't that trigger a different output message? Namely, shouldn't it say ERROR opening socket rather than ERROR on accept?

bzero((char *) &serv_addr, sizeof(serv_addr));
portno = atoi(argv[1]);
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = INADDR_ANY;
serv_addr.sin_port = htons(portno);
if (bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0) 
      error("ERROR on binding");
listen(sockfd,5);
clilen = sizeof(cli_addr);
newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr, &clilen);
if (newsockfd < 0) 
    error("ERROR on accept");

Upvotes: 1

Views: 4762

Answers (2)

sarnold
sarnold

Reputation: 104020

accept(2) does not make sense for a connectionless datagram protocol such as UDP. accept(2) is only for SOCK_STREAM and SOCK_SEQPACKET protocols.

You can connect(2) a UDP protocol to ask the kernel to provide more filtering but this is not always desirable.

Upvotes: 0

James M
James M

Reputation: 16718

UDP is connectionless. Why would you be calling accept?

Upvotes: 7

Related Questions