commit 0007faaa1c4a3333a2410f621b96dddfbf5b3a42
parent a54629ade1ef58d44e9bfe0ab3b3e02115e81ff0
Author: benjamin paul <bpaul@bpaul.xyz>
Date: Sun, 1 Aug 2021 17:33:40 +1000
weird memory stuff for tcp reading socket
Diffstat:
4 files changed, 24 insertions(+), 10 deletions(-)
diff --git a/http.c b/http.c
@@ -13,7 +13,7 @@ respond(char *payload) {
"\n"
"%s";
- length = snprintf(NULL, 0, format, strlen(payload), payload);
+ length = snprintf(NULL, 0, format, strlen(payload), payload);
response = malloc(length);
sprintf(response, format, strlen(payload), payload);
diff --git a/main.c b/main.c
@@ -1,11 +1,10 @@
-#include <stdlib.h>
+#include "http.h"
+#include "tcp.h"
#include <stdio.h>
+#include <stdlib.h>
#include <string.h>
#include <unistd.h>
-#include "http.h"
-#include "tcp.h"
-
int
main() {
int sock, asock;
@@ -28,5 +27,8 @@ main() {
char *text = respond(buf);
write(asock, text, strlen(text));
+
+ free(request);
+ free(text);
}
}
diff --git a/tcp.c b/tcp.c
@@ -10,9 +10,11 @@
#include <sys/stat.h>
#include <unistd.h>
-#define PORT 8000
+#define PORT 8000
#define BACKLOG 50
+#define BUF_SIZE 1024
+
int
create_socket() {
int sock;
@@ -62,11 +64,22 @@ accept_socket(int sock) {
char *
read_socket(int sock) {
- char *buf = malloc(1024);
+ char *buf, *buf2;
+ ssize_t read_size, cur_size = 0;
+
+ buf = malloc(BUF_SIZE);
+ buf2 = malloc(BUF_SIZE);
+
+ memset(buf, 0, BUF_SIZE);
- memset(buf, 0, 1024);
+ /* Keep reading until done */
+ do {
+ read_size = recv(sock, buf2, BUF_SIZE, 0);
+ cur_size += read_size;
- recv(sock, buf, 1024, 0);
+ buf = realloc(buf, cur_size);
+ strcat(buf, buf2);
+ } while (read_size == BUF_SIZE);
return buf;
}
diff --git a/tcp.h b/tcp.h
@@ -1,6 +1,5 @@
#pragma once
-
int create_socket();
int accept_socket(int sock);
char *read_socket(int sock);