diff seobeo/s_linux_network.c @ 3:2758f5527d2b

[Seobeo] Working on simple TCP server and client logic.
author June Park <parkjune1995@gmail.com>
date Wed, 24 Sep 2025 18:49:09 -0700
parents adcfad6e86fb
children 0b3b4f5887bb
line wrap: on
line diff
--- a/seobeo/s_linux_network.c	Wed Sep 24 13:15:32 2025 -0700
+++ b/seobeo/s_linux_network.c	Wed Sep 24 18:49:09 2025 -0700
@@ -98,3 +98,51 @@
   return sock_fd;
 }
 
+
+void Seobeo_ListenClient(int sock_fd, void (*handle_client)(int))
+{
+  int32 client_fd;
+  struct sockaddr_storage client_addr; 
+  socklen_t sin_size;
+
+  char client_inet_addr[INET6_ADDRSTRLEN];
+
+  while (1) 
+  {
+    sin_size = sizeof(client_addr);
+    client_fd = accept(sock_fd, (struct sockaddr *)&client_addr, &sin_size);
+
+    if (client_fd == -1)
+    {
+      perror("accept");
+      break;
+    }
+
+    inet_ntop(
+        client_addr.ss_family,
+        Seobeo_GetIP4OrIP6((struct sockaddr *)&client_addr),
+        client_inet_addr, sizeof client_inet_addr);
+
+    printf("server: got connection from %s\n", client_inet_addr);
+
+    // Create a child process
+    if (!fork())
+    {
+      close(sock_fd);
+      handle_client(client_fd);
+      exit(0);
+    }
+
+    close(client_fd);
+  }
+}
+
+void *Seobeo_GetIP4OrIP6(struct sockaddr *sa)
+{
+  if (sa->sa_family == AF_INET) 
+  {
+    return &(((struct sockaddr_in*)sa)->sin_addr);
+  }
+
+  return &(((struct sockaddr_in6*)sa)->sin6_addr);
+}