]> git.seodisparate.com - c_simple_http/commitdiff
WIP Impl. receiving and printing received ASCII
authorStephen Seo <seo.disparate@gmail.com>
Thu, 29 Aug 2024 07:00:49 +0000 (16:00 +0900)
committerStephen Seo <seo.disparate@gmail.com>
Thu, 29 Aug 2024 07:00:49 +0000 (16:00 +0900)
src/constants.h [new file with mode: 0644]
src/main.c

diff --git a/src/constants.h b/src/constants.h
new file mode 100644 (file)
index 0000000..9159148
--- /dev/null
@@ -0,0 +1,7 @@
+#ifndef SEODISPARATE_COM_C_SIMPLE_HTTP_CONSTANTS_H_
+#define SEODISPARATE_COM_C_SIMPLE_HTTP_CONSTANTS_H_
+
+#define C_SIMPLE_HTTP_SLEEP_NANOS 1000000
+#define C_SIMPLE_HTTP_RECV_BUF_SIZE 1024
+
+#endif
index f9d0ecd80b132bac987d5b301c608cbb60577b14..b918c406c0ea3da42a64e6e09897961514e75e70 100644 (file)
@@ -4,8 +4,12 @@
 #include <stdio.h>
 
 // Unix includes.
+#include <sys/socket.h>
+#include <netinet/in.h>
+#include <unistd.h>
 #include <signal.h>
 #include <time.h>
+#include <errno.h>
 
 // Local includes.
 #include "arg_parse.h"
@@ -13,8 +17,7 @@
 #include "tcp_socket.h"
 #include "signal_handling.h"
 #include "globals.h"
-
-#define C_SIMPLE_HTTP_SLEEP_NANOS 1000000
+#include "constants.h"
 
 int main(int argc, char **argv) {
   Args args = parse_args(argc, argv);
@@ -27,12 +30,48 @@ int main(int argc, char **argv) {
   struct timespec sleep_time;
   sleep_time.tv_sec = 0;
   sleep_time.tv_nsec = C_SIMPLE_HTTP_SLEEP_NANOS;
+
+  struct sockaddr_in6 peer_info;
+  memset(&peer_info, 0, sizeof(struct sockaddr_in6));
+  peer_info.sin6_family = AF_INET6;
+
   signal(SIGINT, C_SIMPLE_HTTP_handle_sigint);
+
+  unsigned char recv_buf[C_SIMPLE_HTTP_RECV_BUF_SIZE];
+
+  int ret;
+  ssize_t read_ret;
+  socklen_t socket_len;
+
   while (C_SIMPLE_HTTP_KEEP_RUNNING) {
     nanosleep(&sleep_time, NULL);
+    socket_len = sizeof(struct sockaddr_in6);
+    ret = accept(tcp_socket, (struct sockaddr *)&peer_info, &socket_len);
+    if (ret == -1 && (errno == EAGAIN || errno == EWOULDBLOCK)) {
+      // No connecting peers, do nothing.
+    } else if (ret == -1) {
+      printf("WARNING: accept: errno %d\n", errno);
+    } else if (ret >= 0) {
+      // Received connection, handle it.
+      int connection_fd = ret;
+      read_ret = read(connection_fd, recv_buf, C_SIMPLE_HTTP_RECV_BUF_SIZE);
+      // DEBUG print received buf.
+      // TODO Validate request and send response.
+      for (unsigned int idx = 0; idx < C_SIMPLE_HTTP_RECV_BUF_SIZE && idx < read_ret; ++idx) {
+        if (recv_buf[idx] >= 0x20 && recv_buf[idx] <= 0x7E) {
+          printf("%c", recv_buf[idx]);
+        } else {
+          break;
+        }
+      }
+      puts("");
+      close(connection_fd);
+    } else {
+      printf("WARNING: accept: Unknown invalid state!\n");
+    }
 #ifndef NDEBUG
-    printf(".");
-    fflush(stdout);
+    //printf(".");
+    //fflush(stdout);
 #endif
   }