静态网页服务器,发送html文件内容
1.创建index.html
1 2 3 4 5 6 7 8 9 10 11 12 13
| <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Page Title</title> </head> <body>
<h1>This is a Heading</h1> <p>This is a paragraph.</p>
</body> </html>
|
2.创建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 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
| #include <sys/socket.h> #include <string.h> #include <unistd.h> #include <netinet/in.h> #include <stdio.h> #include <arpa/inet.h> #include <fcntl.h> #include <sys/stat.h> #include <sys/sendfile.h> #define PORT 8080
int main() { int s = socket(AF_INET, SOCK_STREAM, 0); if (s < 0) { perror("socket"); return 1; }
int opt = 1; setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
struct sockaddr_in addr; memset(&addr, 0, sizeof(addr)); addr.sin_family = AF_INET; addr.sin_port = htons(PORT); addr.sin_addr.s_addr = INADDR_ANY;
if (bind(s, (struct sockaddr*)&addr, sizeof(addr)) < 0) { perror("bind"); return 1; }
if (listen(s, SOMAXCONN) < 0) { perror("listen"); return 1; }
printf("Server running on http://0.0.0.0:%d\n", PORT);
while (1) { int client_fd = accept(s, NULL, NULL); if (client_fd < 0) { perror("accept"); continue; }
char buffer[2048] = {0}; recv(client_fd, buffer, sizeof(buffer), 0);
int fd = open("index.html", O_RDONLY); if (fd < 0) { const char *err = "HTTP/1.1 404 Not Found\r\n" "Content-Type: text/plain\r\n" "Content-Length: 13\r\n" "Connection: close\r\n\r\n" "404 Not Found"; write(client_fd, err, strlen(err)); close(client_fd); continue; }
struct stat st; fstat(fd, &st); size_t filesize = st.st_size;
char header[256]; int len = snprintf(header, sizeof(header), "HTTP/1.1 200 OK\r\n" "Content-Type: text/html\r\n" "Content-Length: %zu\r\n" "Connection: close\r\n\r\n", filesize ); write(client_fd, header, len);
off_t offset = 0; while (offset < filesize) { ssize_t sent = sendfile(client_fd, fd, &offset, filesize - offset); if (sent <= 0) break; }
close(fd); close(client_fd); }
close(s); return 0; }
|
3.编译运行
4.浏览器或curl访问http://127.0.0.1:8080
5.访问成功