-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathhttpserver.c
99 lines (94 loc) · 2.82 KB
/
httpserver.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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
/* Copyright (c) [2023] [Syswonder Community]
* [Ruxos] is licensed under Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
* http://license.coscl.org.cn/MulanPSL2
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/socket.h>
const char header[] = "\
HTTP/1.1 200 OK\r\n\
Content-Type: text/html\r\n\
Content-Length: %u\r\n\
Connection: close\r\n\
\r\n\
";
const char content[] = "<html>\n\
<head>\n\
<title>Hello, Ruxos</title>\n\
</head>\n\
<body>\n\
<center>\n\
<h1>Hello, <a href=\"https://github.com/syswonder/ruxos\">Ruxos</a></h1>\n\
</center>\n\
<hr>\n\
<center>\n\
<i>Powered by <a href=\"https://github.com/syswonder/ruxos/tree/main/apps/net/httpserver\">Ruxos example HTTP server</a> v0.1.0</i>\n\
</center>\n\
</body>\n\
</html>\n\
";
int main()
{
puts("Hello, Ruxos C HTTP server!");
struct sockaddr_in local, remote;
int addr_len = sizeof(remote);
local.sin_family = AF_INET;
if (inet_pton(AF_INET, "0.0.0.0", &(local.sin_addr)) != 1) {
perror("inet_pton() error");
return -1;
}
local.sin_port = htons(5555);
int sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (sock == -1) {
perror("socket() error");
return -1;
}
if (bind(sock, (struct sockaddr *)&local, sizeof(local)) != 0) {
perror("bind() error");
return -1;
}
if (listen(sock, 0) != 0) {
perror("listen() error");
return -1;
}
puts("listen on: http://0.0.0.0:5555/");
char buf[1024] = {};
int client;
char response[1024] = {};
snprintf(response, 1024, header, strlen(content));
strcat(response, content);
for (;;) {
client = accept(sock, (struct sockaddr *)&remote, (socklen_t *)&addr_len);
if (client == -1) {
perror("accept() error");
return -1;
}
printf("new client %d\n", client);
if (recv(client, buf, 1024, 0) == -1) {
perror("recv() error");
return -1;
}
ssize_t l = send(client, response, strlen(response), 0);
if (l == -1) {
perror("send() error");
return -1;
}
if (close(client) == -1) {
perror("close() error");
return -1;
}
printf("client %d close: %ld bytes sent\n", client, l);
}
if (close(sock) == -1) {
perror("close() error");
return -1;
}
return 0;
}