Created
December 18, 2025 21:43
-
-
Save leanghok120/c170837ce7f959103b52b50ebe322186 to your computer and use it in GitHub Desktop.
http server in c
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <stdio.h> | |
| #include <stdlib.h> | |
| #include <string.h> | |
| #include <unistd.h> | |
| #include <sys/socket.h> | |
| #include <netinet/in.h> | |
| #include <arpa/inet.h> | |
| #define PORT 80 | |
| int sockfd; | |
| struct sockaddr_in sockaddr; | |
| void die(char *message) { | |
| perror(message); | |
| exit(EXIT_FAILURE); | |
| } | |
| void set_socket_reuse() { | |
| int optval = 1; | |
| setsockopt(sockfd, SOL_SOCKET, SO_REUSEPORT, &optval, sizeof(optval)); | |
| setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval)); | |
| } | |
| void init_socket() { | |
| sockfd = socket(AF_INET, SOCK_STREAM, 0); | |
| if (sockfd == -1) { | |
| perror("socket"); | |
| exit(EXIT_FAILURE); | |
| } | |
| sockaddr.sin_addr.s_addr = inet_addr("127.0.0.1"); | |
| sockaddr.sin_port = htons(PORT); | |
| sockaddr.sin_family = AF_INET; | |
| int err = bind(sockfd, (struct sockaddr *)&sockaddr, sizeof(sockaddr)); | |
| if (err == -1) { | |
| die("bind"); | |
| } | |
| err = listen(sockfd, 5); | |
| if (err == -1) { | |
| die("listen"); | |
| } | |
| printf("server running on port: %d\n\n", PORT); | |
| } | |
| void handle_con() { | |
| while (1) { | |
| int clientfd = accept(sockfd, NULL, NULL); | |
| if (clientfd == -1) { | |
| die("accept"); | |
| } | |
| char buf[1024]; | |
| while (1) { | |
| // read request | |
| memset(buf, '\0', sizeof(buf)); | |
| int err = read(clientfd, buf, sizeof(buf)); | |
| if (err <= 0) { | |
| break; | |
| } | |
| printf("%s\n", buf); | |
| // write response | |
| memset(buf, '\0', sizeof(buf)); | |
| strcpy(buf, | |
| "HTTP/1.1 200 OK\r\n" | |
| "Content-Type: text/plain\r\n" | |
| "Content-Length: 5\r\n" | |
| "Connection: close\r\n" | |
| "\r\n" | |
| "hello" | |
| ); | |
| write(clientfd, buf, strlen(buf)); | |
| printf("%s\n", buf); | |
| close(clientfd); | |
| } | |
| } | |
| } | |
| int main() { | |
| init_socket(); | |
| set_socket_reuse(); | |
| handle_con(); | |
| close(sockfd); | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment