Return response to incoming connections

This commit is contained in:
akp 2023-11-02 17:30:19 +00:00
parent 04513fb2b6
commit 91bcde20e5
No known key found for this signature in database
GPG key ID: CF8D58F3DEB20755

View file

@ -34,12 +34,12 @@ int open_socket(const char *ip, const char *port, int *res_sd) {
return 1;
}
if (bind(sd, addrinfo_res->ai_addr, addrinfo_res->ai_addrlen) == -1) {
if (bind(sd, addrinfo_res->ai_addr, addrinfo_res->ai_addrlen) != 0) {
perror("failed to bind to port");
return 1;
}
if (listen(sd, 5)) {
if (listen(sd, 5) != 0) {
perror("failed to start listening for connections");
return 1;
}
@ -49,17 +49,44 @@ int open_socket(const char *ip, const char *port, int *res_sd) {
return 0;
}
#define MAX_CHUNK_LENGTH 128
void handle_connection(int *sdptr) {
int sd = *sdptr;
fprintf(stderr, "TODO: handle connection %d\n", sd);
char *dat = (char *) malloc(sizeof(char) * 128);
int num_bytes;
while ((num_bytes = recv(sd, dat, MAX_CHUNK_LENGTH, 0)) != 0) {
printf("[DBG %d] got %d bytes\n", sd, num_bytes);
if (num_bytes == -1) {
perror("warning: failed to receive from remote host");
goto cleanup;
}
printf("[LOG %d] %s", sd, dat);
if (num_bytes < MAX_CHUNK_LENGTH) {
break;
}
}
if (send(sd, "lmao cool\n", 10, 0) == -1) {
perror("warning: failed to send data to remote host");
goto cleanup;
}
printf("[END %d]\n", sd);
cleanup:
free(dat);
if (shutdown(sd, 2) != 0) {
perror("warning: shutdown connection in thread failed");
return;
}
if (close(sd) != 0) {
perror("warning: shutdown connection in thread failed");
perror("warning: close connection in thread failed");
return;
}
}