C语言 使用 C 套接字发送 HTTP 响应

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5487297/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 08:13:33  来源:igfitidea点击:

Send HTTP response using C socket

chttpsocketsresponse

提问by spe

I`m trying to send HTTP response to browser

我正在尝试向浏览器发送 HTTP 响应

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?

但是我的浏览器无法理解这一点,等待很长时间然后打印出奇怪的东西。我想我的回答是错误的,但我不知道如何解决。有任何想法吗?

回答by Erik

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

sizeof(reply)计算为 a 的大小char *,也就是指针的大小。使用strlen.

send(client, reply, strlen(reply), 0);