Home > front end >  What's wrong with this code that attempts to listen repeatedly on a socket?
What's wrong with this code that attempts to listen repeatedly on a socket?

Time:07-12

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <netdb.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <pthread.h>
#include <arpa/inet.h>

struct sockaddr_in server, acc;
int sock;

int stuff(void) {
    char buffer[2000];

    recv(sock, buffer, sizeof(buffer), 0);
    send(sock, "HTTP/1.1 200 OK\nContent-Type: text/html\n\nHello", sizeof("HTTP/1.1 200 OK\nContent-Type: text/html\n\nHello"), 0);

    shutdown(sock, SHUT_RDWR);
    
    return 0;
}

int main(void) {
    int size;

    sock = socket(AF_INET, SOCK_STREAM, 0);

    server.sin_family      = AF_INET;
    server.sin_addr.s_addr = INADDR_ANY;
    server.sin_port        = htons(1111);

    if (bind(sock, (struct sockaddr*)&server, sizeof(server)) == -1) {
        perror("Error:");
        return 1;
    }

    while (1) {
        listen(sock, 5);
        sock = accept(sock, (struct sockaddr*)&acc, &size);
        printf("accepted\n");

        stuff();

        close(sock);
    }
}

This is meant to be an extremely basic HTTP server. I don't know what's going wrong, but the connection seems to not end with the client. Opening this in the browser, it doesn't stop loading and the console is flooded with "accepted" (line 42). No new connections can be accepted.

CodePudding user response:

After your program accepts a connection, it forgets about the socket that listens for new connections, does remember the newly connected socket, does some stuff with that socket, closes it, then tries to accept another connection from the connected socket that it just closed.

There are two problems here:

  • It's the wrong socket
  • Even if it was the right socket, it's closed

You create socket number 3 (for example) to wait for new connections. You wait for a connection on socket 3 and the new connection is socket number 4 (for example). Then you do the stuff, then you close socket 4, then you wait for a new connection on socket 4. Do you see the mistake here? Socket 3 is the one that accepts connections.

Since you are not new to programming, you should be able to figure out how to make your program call accept with the right socket.

  • Related