ScrapExplorer - server.c

Home / usr / http_server Lines: 8 | Size: 2665 bytes [Download] [Show on GitHub] [Search similar files] [Raw] [Raw (proxy)]
[FILE BEGIN]
1/* SPDX-License-Identifier: GPL-3.0 2 * http_server 3 * 4 * server.c 5 * 6 * COPYRIGHT NOTICE 7 * Copyright (C) 2024-2025 0x4248 and contributors 8 * Redistribution and use in source and binary forms, with or without 9 * modification, are permitted provided that the license is not changed. 10 * 11 * This software is free and open source. Licensed under the GNU general 12 * public license version 3.0 as published by the Free Software Foundation. 13 */ 14 15#include <stdio.h> 16#include <stdlib.h> 17#include <string.h> 18#include <unistd.h> 19#include <arpa/inet.h> 20 21#define PORT 8080 22#define BUFFER_SIZE 1024 23 24int main() 25{ 26 int server_fd, new_socket; 27 char buffer[BUFFER_SIZE] = {0}; 28 29 struct sockaddr_in address; 30 address.sin_family = AF_INET; 31 address.sin_addr.s_addr = INADDR_ANY; 32 address.sin_port = htons(PORT); 33 34 /** 35 * Create a socket file descriptor 36 */ 37 if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0) 38 { 39 perror("Socket failed"); 40 return -1; 41 } 42 43 /** 44 * Bind the socket to the address and port 45 */ 46 if (bind(server_fd, (struct sockaddr *)&address, sizeof(address)) < 0) 47 { 48 perror("Bind failed"); 49 close(server_fd); 50 return -1; 51 } 52 53 /** 54 * Listen for incoming connections 55 */ 56 if (listen(server_fd, 1) < 0) 57 { 58 perror("Listen failed"); 59 close(server_fd); 60 return -1; 61 } 62 63 printf("Simple HTTP server is running on port %d\n", PORT); 64 65 while (1) 66 { 67 /** 68 * Accept incoming connection 69 */ 70 if ((new_socket = accept(server_fd, (struct sockaddr *)&address, (socklen_t *)&address)) < 0) 71 { 72 perror("Accept failed"); 73 close(server_fd); 74 return -1; 75 } 76 77 /** 78 * Read the request from the client 79 */ 80 read(new_socket, buffer, BUFFER_SIZE); 81 /* At this point we should have a get request */ 82 printf("Received request:\n%s\n", buffer); 83 84 /* TODO: fully parse the request */ 85 86 /** 87 * Basic path parsing 88 */ 89 char *path = strtok(buffer, " "); 90 path = strtok(NULL, " "); 91 92 printf("Requested path: %s\n", path); 93 94 /** 95 * Send a simple HTML response 96 */ 97 char *html_response = "HTTP/1.1 200 OK\nContent-Type: text/html\n\n<!DOCTYPE html><html><head><title>Simple HTTP Server</title></head><body><h1>Hello, World!</h1></body></html>"; 98 99 /** 100 * Send the response to the client and close the connection 101 */ 102 write(new_socket, html_response, strlen(html_response)); 103 close(new_socket); 104 } 105 106 return 0; 107} 108
[FILE END]
(C) 2025 0x4248 (C) 2025 4248 Media and 4248 Systems, All part of 0x4248 See LICENCE files for more information. Not all files are by 0x4248 always check Licencing.