0

I'm trying to make a tiny http server in c but I got CONNRESET errors with httperf, why ?

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <signal.h>

#include <unistd.h>
#include <errno.h>
#include <sys/types.h> 
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <fcntl.h>

#define SOCKERROR -1

#define SD_RECEIVE 0
#define SD_SEND 1
#define SD_BOTH 2

int server;
int client;

...

int main(int argc, char *argv[])
{
    int status;

    int accepted;

    struct addrinfo hint;
    struct addrinfo *info;

    struct sockaddr addr;
    socklen_t addrsize;

    int yes = 1;

    ...

    // client

    addrsize = sizeof addr;

    while (1)
    {
        memset(&accepted, 0, sizeof accepted);
        memset(&addr, 0, sizeof addr);

        accepted = accept(server, &addr, &addrsize);

        if (accepted == SOCKERROR) {
            warn("Accept", errno);
        } else {
            shutdown(accepted, SD_SEND);
            close(accepted);
        }
    }

    // shutdown

    ...

    return EXIT_SUCCESS;
}
bernedef
  • 699
  • 2
  • 12
  • 22
  • httperf will be sending data, your application is ignoring it... I imagine either the perf tool is timing out / buffers are getting full and the connection is getting closed. If you ignore IO being sent to a socket, eventually one side will give up, the OS isn't going to buffer it forever. – forsvarir May 19 '11 at 09:11

2 Answers2

3

You're closing the socket as soon as you accept it. So the connection is reset on the other end of it.

If you want to talk to an HTTP client, you're going to have to parse the incoming HTTP requests, and reply with valid HTTP data. (Warning: that's not trivial.)

Please read this article: nweb: a tiny, safe Web server (static pages only) for example, it has a good rundown of what needs to be done for a minimal HTTP server.

Mat
  • 202,337
  • 40
  • 393
  • 406
  • do I have just to read and send any data to avoid connreset error ? – bernedef May 19 '11 at 09:14
  • @Fabien: of course. if you don't read or write data, at best the client will hang doing nothing. – Mat May 19 '11 at 09:17
  • @Fabien: if you want httperf to "work" with your server, you'll need to implement at least some of the HTTP dialog. You'll need to read the input and reply with a valid HTTP response. That is not something you can do with a "little example of code". – Mat May 19 '11 at 09:22
1

OK, thanks for your help, I've just added this before closing client socket, and no more CONNRESET error :

char readBuffer[128];
char *sendBuffer = "HTTP/1.0 200 OK\r\n"
    "Content-Type: text/html\r\n"
    "Content-Length: 30\r\n\r\n"
    "<html><body>test</body></html>";

do {
    status = recv(accepted, readBuffer, sizeof readBuffer, MSG_DONTWAIT);
} while (status > 0);

send(accepted, sendBuffer, (int) strlen(sendBuffer), 0);
bernedef
  • 699
  • 2
  • 12
  • 22