http网页服务器,发送一句话

需要发送http协议头,浏览器才会解析内容。

1.创建server.c

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#include <sys/socket.h>
#include <string.h>
#include <unistd.h>
#include <netinet/in.h>
#include <stdio.h>
#include <arpa/inet.h>

int main()
{
int s = socket(AF_INET,SOCK_STREAM,0);
// Reuse address
int opt = 1;
setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
struct sockaddr_in addr={
AF_INET,
htons(8080),
0
};
bind(s, (struct sockaddr*)&addr, sizeof(addr));
listen(s, 10);

while(1)
{
int client_fd = accept(s, 0, 0);

char buffer[1024] = {0};
recv(client_fd, buffer, sizeof(buffer) - 1, 0);

// GET
char header[256];
const char *body = "Hello from C server!\n";
int len = snprintf(header, sizeof(header),
"HTTP/1.1 200 OK\r\n"
"Content-Type: text/plain\r\n"
"Content-Length: %zu\r\n"
"Connection: close\r\n\r\n",
strlen(body)
);

write(client_fd, header, len);
write(client_fd, body, strlen(body));

close(client_fd);
}
close(s);

return 0;
}

2.编译运行

1
2
gcc server.c
./a.out

3.浏览器或者curl命令访问