Mercurial
comparison 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 |
comparison
equal
deleted
inserted
replaced
| 2:8a43dedbe530 | 3:2758f5527d2b |
|---|---|
| 96 } | 96 } |
| 97 | 97 |
| 98 return sock_fd; | 98 return sock_fd; |
| 99 } | 99 } |
| 100 | 100 |
| 101 | |
| 102 void Seobeo_ListenClient(int sock_fd, void (*handle_client)(int)) | |
| 103 { | |
| 104 int32 client_fd; | |
| 105 struct sockaddr_storage client_addr; | |
| 106 socklen_t sin_size; | |
| 107 | |
| 108 char client_inet_addr[INET6_ADDRSTRLEN]; | |
| 109 | |
| 110 while (1) | |
| 111 { | |
| 112 sin_size = sizeof(client_addr); | |
| 113 client_fd = accept(sock_fd, (struct sockaddr *)&client_addr, &sin_size); | |
| 114 | |
| 115 if (client_fd == -1) | |
| 116 { | |
| 117 perror("accept"); | |
| 118 break; | |
| 119 } | |
| 120 | |
| 121 inet_ntop( | |
| 122 client_addr.ss_family, | |
| 123 Seobeo_GetIP4OrIP6((struct sockaddr *)&client_addr), | |
| 124 client_inet_addr, sizeof client_inet_addr); | |
| 125 | |
| 126 printf("server: got connection from %s\n", client_inet_addr); | |
| 127 | |
| 128 // Create a child process | |
| 129 if (!fork()) | |
| 130 { | |
| 131 close(sock_fd); | |
| 132 handle_client(client_fd); | |
| 133 exit(0); | |
| 134 } | |
| 135 | |
| 136 close(client_fd); | |
| 137 } | |
| 138 } | |
| 139 | |
| 140 void *Seobeo_GetIP4OrIP6(struct sockaddr *sa) | |
| 141 { | |
| 142 if (sa->sa_family == AF_INET) | |
| 143 { | |
| 144 return &(((struct sockaddr_in*)sa)->sin_addr); | |
| 145 } | |
| 146 | |
| 147 return &(((struct sockaddr_in6*)sa)->sin6_addr); | |
| 148 } |