Last active
June 10, 2018 08:29
-
-
Save PeskyPotato/e6aa84c6792ae34edbda922d1aecb4d8 to your computer and use it in GitHub Desktop.
A simple 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 <sys/socket.h> | |
#include <sys/types.h> | |
#include <netinet/in.h> | |
int main() { | |
// Char array to hold html file text | |
char html_data[1024]; | |
FILE *fp = fopen("index.html", "r"); | |
fread(html_data, 1024, 1, fp); | |
// Add null terminator at the end | |
html_data[1024] = '\0'; | |
// HTTP Status Code 200 means request has been succeeded | |
char http_header[2048] = "HTTP/1.1 200 OK\r\n\n"; | |
// Concatonate header and data | |
strcat(http_header, html_data); | |
// Create socket | |
int server_socket; | |
server_socket = socket(AF_INET, SOCK_STREAM, 0); | |
// Define server address | |
struct sockaddr_in server_address; | |
server_address.sin_family = AF_INET; // Address family (IPv4) | |
server_address.sin_port = htons(8000); // Port | |
server_address.sin_addr.s_addr = htons(INADDR_ANY); //Binds the socket all interfaces | |
// Bind the socket to the IP address and port | |
bind(server_socket, (struct sockaddr *) &server_address, sizeof(server_address)); | |
// Listen for connections on the socket | |
listen(server_socket, 5); | |
// Placeholder for client socket | |
int client_socket; | |
// Infinitely serve | |
while(1) { | |
// Accept connections | |
client_socket = accept(server_socket, NULL, NULL); | |
if (client_socket < 0) | |
printf("Error on client socket"); | |
// Send | |
send(client_socket, http_header, sizeof(http_header), 0); | |
close(client_socket); | |
} | |
return 0; | |
} |
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
<html> | |
<body> | |
My first HTTP server! | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment