make hello.c a server that echos things

This commit is contained in:
Greg Burd 2023-09-13 14:36:27 -04:00
parent 1be0e51b91
commit 16264c302a
No known key found for this signature in database
GPG key ID: 1FC1E7793410DE46
2 changed files with 70 additions and 9 deletions

View file

@ -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; };
}
);
}

71
hello.c
View file

@ -1,6 +1,69 @@
#include "stdio.h"
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
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;
}