RyanHub – file viewer
filename: server.c
branch: main
back to repo
// server.c

#ifdef _WIN32
#define _WIN32_WINNT 0x0601
#include <winsock2.h>
#include <ws2tcpip.h>
#pragma comment(lib, "Ws2_32.lib")
#else
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#define SOCKET int
#define INVALID_SOCKET -1
#define closesocket close
#endif

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main() {
#ifdef _WIN32
    WSADATA wsa;
    WSAStartup(MAKEWORD(2,2), &wsa);
#endif

    SOCKET server_sock = socket(AF_INET, SOCK_STREAM, 0);

    struct sockaddr_in server_addr = {
        .sin_family = AF_INET,
        .sin_port = htons(8080),
        .sin_addr.s_addr = INADDR_ANY
    };

    bind(server_sock, (struct sockaddr*)&server_addr, sizeof(server_addr));
    listen(server_sock, 5);

    while (1) {
        SOCKET client_sock = accept(server_sock, NULL, NULL);
        if (client_sock == INVALID_SOCKET) continue;

        char buffer[1024] = {0};
        recv(client_sock, buffer, sizeof(buffer) - 1, 0);

        printf("Message:\n%s\n", buffer);

		if (strncmp(buffer, "GET / ", 6) == 0 || strncmp(buffer, "GET /index.html", 15) == 0) {
			FILE* f = fopen("index.html", "rb");
			if (f) {
				fseek(f, 0, SEEK_END);
				long filesize = ftell(f);
				rewind(f);

				char* filebuf = malloc(filesize);
				fread(filebuf, 1, filesize, f);
				fclose(f);

				char header[256];
				int header_len = snprintf(
					header, sizeof(header),
					"HTTP/1.1 200 OK\r\n"
					"Content-Type: text/html\r\n"
					"Content-Length: %ld\r\n"
					"\r\n",
					filesize
				);

				send(client_sock, header, header_len, 0);
				send(client_sock, filebuf, filesize, 0);

				free(filebuf);
			} else {
				const char* not_found = "HTTP/1.1 404 Not Found\r\nContent-Length: 9\r\n\r\nNot Found";
				send(client_sock, not_found, (int)strlen(not_found), 0);
			}
		} else {
			const char* not_found = "HTTP/1.1 404 Not Found\r\nContent-Length: 9\r\n\r\nNot Found";
			send(client_sock, not_found, (int)strlen(not_found), 0);
		}


        closesocket(client_sock);
    }

#ifdef _WIN32
    WSACleanup();
#endif

    return 0;
}