Created
January 5, 2020 20:12
-
-
Save skejeton/8eb3ffa5c303e0d44ae423653100f1f5 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 "server.c" | |
char *body = "<a>href='#'>Test</a>"; | |
char *res = strcat(strcat("HTTP/1.1 200 OK\nDate: Mon, 27 Jul 2019 12:28:53 GMT\nServer: Apache/2.2.14 (Win32)\nLast-Modified: Wed, 22 Jul 2009 19:15:56 GMT\nContent-Length: ", str(strlen(body))), "\nContent-Type: text/html\nConnection: Closed\nContent-Type: text/html; charset=utf-8\n\n"); | |
int handle_conn(int sock) | |
{ | |
write(sock, res, strlen(res)); | |
} | |
int main() | |
{ | |
HTTPServer serv; | |
HTTPServerHost(&serv, 8050); | |
HTTPServerOnConnect(&serv, &handle_conn); | |
} |
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
#pragma once | |
#include <sys/socket.h> | |
#include <sys/types.h> | |
#include <netinet/in.h> | |
#include <arpa/inet.h> | |
#include <stdlib.h> | |
#include <stdio.h> | |
#define HTTP_ERR_SOCKINIT 1 | |
#define HTTP_ERR_SOCKBIND 2 | |
#define HTTP_ERR_SOCKLSTN 3 | |
typedef struct { | |
unsigned int port; | |
int sockId; | |
} HTTPServer; | |
void HTTPServerHost(HTTPServer *server, unsigned int port) | |
{ | |
server->port = port; | |
server->sockId = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP); | |
if (server->sockId == -1) | |
{ | |
return HTTP_ERR_SOCKINIT; | |
} | |
// Initializing socket address | |
struct sockaddr_in addr; | |
memset(&addr, 0, sizeof(addr)); | |
addr.sin_family = AF_INET; | |
addr.sin_port = htons(port); | |
addr.sin_addr.s_addr = htonl(INADDR_ANY); | |
if (bind(server->sockId, (struct sockaddr*) &addr, sizeof addr) == -1) | |
{ | |
return HTTP_ERR_SOCKBIND; | |
} | |
if (listen(server->sockId, 10) == -1) | |
{ | |
return HTTP_ERR_SOCKLSTN; | |
} | |
} | |
void HTTPServerOnConnect(HTTPServer *server, int (*handler)(int)) | |
{ | |
for (;;) { | |
int ConnectFD = accept(server->sockId, NULL, NULL); | |
if (0 > ConnectFD) { | |
perror("accept failed"); | |
close(server->sockId); | |
exit(EXIT_FAILURE); | |
} | |
handler(ConnectFD); | |
if (shutdown(ConnectFD, SHUT_RDWR) == -1) { | |
perror("shutdown failed"); | |
close(ConnectFD); | |
close(server->sockId); | |
exit(EXIT_FAILURE); | |
} | |
close(ConnectFD); | |
} | |
close(server->sockId); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment