使用C套接字发送HTTP响应

时间:2011-03-30 13:54:52

标签: c http sockets response

我正在尝试向浏览器发送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);
    }
}

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

1 个答案:

答案 0 :(得分:8)

sizeof(reply)计算为char *的大小,即指针的大小。使用strlen

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