6

I`m trying to send HTTP response to browser

char *reply = 
"HTTP/1.1 200 OK\n"
"Date: Thu, 19 Feb 2009 12:27:04 GMT\n"
"Server: Apache/2.2.3\n"
"Last-Modified: Wed, 18 Jun 2003 16:05:58 GMT\n"
"ETag: \"56d-9989200-1132c580\"\n"
"Content-Type: text/html\n"
"Content-Length: 15\n"
"Accept-Ranges: bytes\n"
"Connection: close\n"
"\n"
"sdfkjsdnbfkjbsf";

int sd = socket(PF_INET, SOCK_STREAM, 0);

struct sockaddr_in addr;
bzero(&addr, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_port = htons(8081);
addr.sin_addr.s_addr = INADDR_ANY;

if(bind(sd,&addr,sizeof(addr))!=0)
{
    printf("bind error\n");
}

if (listen(sd, 16)!=0)
{
    printf("listen error\n");
}

for(;;)
{
    int size = sizeof(addr);
    int client = accept(sd, &addr, &size);

    if (client > 0)
    {
        printf("client connected\n");
        send(client, reply, sizeof(reply), 0);
    }
}

but my browser cant understand this, waits for a long time and then print smth strange. I guess my response is wrong, but I dont know how to fix. Any ideas?

2
  • should use strlen(reply), and add close(client) Commented Jul 3, 2019 at 2:51
  • maybe you also need a \r "HTTP/1.1 200 OK\r\n" Commented Feb 13, 2023 at 22:10

1 Answer 1

10

sizeof(reply) evaluates to the size of a char *, aka size of a pointer. Use strlen.

send(client, reply, strlen(reply), 0);
Sign up to request clarification or add additional context in comments.

1 Comment

Damn! Stupid mistake. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.