Created
February 3, 2024 20:47
-
-
Save Yggdrasill501/74cc28169d99b7100bf05da6dcca2291 to your computer and use it in GitHub Desktop.
Simplest web socket for creating web-server in C
This file contains 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 <string.h> | |
#include <sys/socket.h> | |
#include <netinet/in.h> | |
#include <unistd.h> | |
int main() { | |
int server_fd, new_socket; | |
struct sockaddr_in address; | |
int addrlen = sizeof(address); | |
char buffer[1024] = {0}; | |
char *response = "HTTP/1.1 200 OK\nContent-Type: text/plain\nContent-Length: 15\n\nI am web server"; | |
if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0) { | |
perror("socket failed"); | |
exit(EXIT_FAILURE); | |
} | |
address.sin_family = AF_INET; | |
address.sin_addr.s_addr = INADDR_ANY; | |
address.sin_port = htons(8000); | |
if (bind(server_fd, (struct sockaddr *)&address, sizeof(address)) < 0) { | |
perror("bind failed"); | |
exit(EXIT_FAILURE); | |
} | |
if (listen(server_fd, 3) < 0) { | |
perror("listen"); | |
exit(EXIT_FAILURE); | |
} | |
if ((new_socket = accept(server_fd, (struct sockaddr *)&address, (socklen_t*)&addrlen)) < 0) { | |
perror("accept"); | |
exit(EXIT_FAILURE); | |
} | |
read(new_socket, buffer, 1024); | |
printf("Request:\n%s\n", buffer); | |
send(new_socket, response, strlen(response), 0); | |
printf("Response sent\n"); | |
// Close the socket | |
close(new_socket); | |
close(server_fd); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment