Skip to content

Instantly share code, notes, and snippets.

@GOROman
Created March 3, 2025 22:16
Show Gist options
  • Save GOROman/94d9ca2ea4333d1f7e9497bfa82b3a12 to your computer and use it in GitHub Desktop.
Save GOROman/94d9ca2ea4333d1f7e9497bfa82b3a12 to your computer and use it in GitHub Desktop.
超高機能 Web Server
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#define PORT 8080
#define BUFFER_SIZE 1024
int main() {
int server_fd, new_socket;
struct sockaddr_in address;
int addrlen = sizeof(address);
char buffer[BUFFER_SIZE] = {0};
// HTTP response with "hello, world" in H1 tag
char *http_response = "HTTP/1.1 200 OK\r\n"
"Content-Type: text/html\r\n"
"Connection: close\r\n"
"\r\n"
"<!DOCTYPE html>\r\n"
"<html>\r\n"
"<head>\r\n"
" <title>Simple C Web Server</title>\r\n"
"</head>\r\n"
"<body>\r\n"
" <h1>hello, world</h1>\r\n"
"</body>\r\n"
"</html>\r\n";
// Creating socket file descriptor
if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0) {
perror("Socket creation failed");
exit(EXIT_FAILURE);
}
// Set socket options to reuse address and port
int opt = 1;
if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt))) {
perror("Setsockopt failed");
exit(EXIT_FAILURE);
}
// Set up server address structure
address.sin_family = AF_INET;
address.sin_addr.s_addr = INADDR_ANY;
address.sin_port = htons(PORT);
// Bind the socket to the specified port
if (bind(server_fd, (struct sockaddr *)&address, sizeof(address)) < 0) {
perror("Bind failed");
exit(EXIT_FAILURE);
}
// Listen for incoming connections
if (listen(server_fd, 3) < 0) {
perror("Listen failed");
exit(EXIT_FAILURE);
}
printf("Server running on port %d...\n", PORT);
while (1) {
printf("Waiting for a connection...\n");
// Accept an incoming connection
if ((new_socket = accept(server_fd, (struct sockaddr *)&address, (socklen_t*)&addrlen)) < 0) {
perror("Accept failed");
exit(EXIT_FAILURE);
}
// Read the incoming request
read(new_socket, buffer, BUFFER_SIZE);
printf("Request received:\n%s\n", buffer);
// Send HTTP response
write(new_socket, http_response, strlen(http_response));
printf("Response sent\n");
// Close the connection
close(new_socket);
}
return 0;
}
@GOROman
Copy link
Author

GOROman commented Mar 3, 2025

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment