Last active
January 25, 2021 03:39
-
-
Save leandronsp/1626f2f9be403b325734a522432bcd9b to your computer and use it in GitHub Desktop.
HTTP 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 <stdio.h> | |
#include <netinet/in.h> | |
#include <stdlib.h> | |
#include <sys/socket.h> | |
#include <unistd.h> | |
#define MAXBUFFER 3000 | |
#define PORT 4200 | |
int main () { | |
struct sockaddr_in servaddr = {}; | |
int sockfd = socket(AF_INET, SOCK_STREAM, 0); | |
if (sockfd == -1) { | |
printf("Socket creation failed...\n"); | |
exit(0); | |
} | |
if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &(int){1}, sizeof(int)) < 0) { | |
printf("setsockopt(SO_REUSEADDR) failed\n"); | |
exit(0); | |
} | |
servaddr.sin_family = AF_INET; | |
servaddr.sin_addr.s_addr = htonl(INADDR_ANY); | |
servaddr.sin_port = htons(PORT); | |
if ((bind(sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr))) != 0) { | |
printf("Failed to bind socket\n"); | |
exit(0); | |
} | |
if (listen(sockfd, 5) != 0) { | |
printf("Listen failed\n"); | |
exit(0); | |
} | |
printf("Server listening...\n"); | |
int addrlen = sizeof(servaddr); | |
int connfd; | |
for (;;) { | |
connfd = accept(sockfd, (struct sockaddr *)&servaddr, (socklen_t*)&addrlen); | |
if (connfd < 0) { | |
printf("Accept failed: %d\n", connfd); | |
exit(0); | |
} | |
char request[MAXBUFFER] = {0}; | |
read(connfd, request, sizeof(request)); | |
printf("Request: %s\n", request); | |
char response[MAXBUFFER] = "HTTP/1.1 200\r\nContent-Type: text/html\r\n\r\n<h1>Hello!</h1>"; | |
write(connfd, response, sizeof(response)); | |
printf("Response: %s\n", response); | |
close(connfd); | |
} | |
close(sockfd); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment