From 16264c302a3933a1ea0d076697592ea99028be9f Mon Sep 17 00:00:00 2001 From: Greg Burd Date: Wed, 13 Sep 2023 14:36:27 -0400 Subject: [PATCH] make hello.c a server that echos things --- flake.nix | 8 +++---- hello.c | 71 +++++++++++++++++++++++++++++++++++++++++++++++++++---- 2 files changed, 70 insertions(+), 9 deletions(-) diff --git a/flake.nix b/flake.nix index 59fec95..1071f2a 100644 --- a/flake.nix +++ b/flake.nix @@ -12,10 +12,8 @@ outputs = { self, nixpkgs, flake-utils }: let - lastModifiedDate = self.lastModifiedDate or self.lastModified or "19700101"; - - # Generate a user-friendly version number (e.g. "1.2.3-20231027-DIRTY"). - version = "${builtins.readFile ./VERSION.txt}.${builtins.substring 0 8 (self.lastModifiedDate or "19700101")}.${self.shortRev or "DIRTY"}"; + # Generate a user-friendly version number (e.g. "1.2.3-DIRTY"). + version = "${builtins.readFile ./VERSION.txt}${self.shortRev or "DIRTY"}"; # System types to support. supportedSystems = [ "x86_64-linux" "x86_64-darwin" "aarch64-linux" "aarch64-darwin" ]; @@ -50,7 +48,7 @@ packages.container = pkgs.callPackage ./container.nix { package = packages.default; }; apps.hello = flake-utils.lib.mkApp { drv = packages.default; }; defaultApp = apps.hello; -# devShells.default = import ./shell.nix { inherit pkgs; }; + devShells.default = import ./shell.nix { inherit pkgs; }; } ); } diff --git a/hello.c b/hello.c index cb63c86..73bc705 100644 --- a/hello.c +++ b/hello.c @@ -1,6 +1,69 @@ -#include "stdio.h" +#include +#include +#include +#include +#include -int main(int argc, char **argv) -{ - printf("Hello, world!\n"); +int echo() { + int listen_socket, client_socket; + struct sockaddr_in listen_addr, client_addr; + socklen_t client_addr_len; + char buffer[1024]; + int bytes_received; + + // Create a socket + listen_socket = socket(AF_INET, SOCK_STREAM, 0); + if (listen_socket < 0) { + perror("socket"); + exit(1); + } + + // Bind the socket to port 5001 + listen_addr.sin_family = AF_INET; + listen_addr.sin_port = htons(5001); + listen_addr.sin_addr.s_addr = INADDR_ANY; + if (bind(listen_socket, (struct sockaddr *)&listen_addr, sizeof(listen_addr)) < 0) { + perror("bind"); + exit(1); + } + + // Listen for connections + listen(listen_socket, 5); + + // Accept a connection + client_addr_len = sizeof(client_addr); + client_socket = accept(listen_socket, (struct sockaddr *)&client_addr, &client_addr_len); + if (client_socket < 0) { + perror("accept"); + exit(1); + } + + // Echo the data back to the client + while (1) { + bytes_received = recv(client_socket, buffer, sizeof(buffer), 0); + if (bytes_received < 0) { + perror("recv"); + exit(1); + } + + if (bytes_received == 0) { + // The client has closed the connection + break; + } + + send(client_socket, buffer, bytes_received, 0); + } + + // Close the sockets + close(listen_socket); + close(client_socket); + + return 0; +} + +int main() { + while (1) { + echo(); + } + return 0; }