aboutsummaryrefslogtreecommitdiff
path: root/tests/sockets/test_sockets_msg.h
diff options
context:
space:
mode:
Diffstat (limited to 'tests/sockets/test_sockets_msg.h')
-rw-r--r--tests/sockets/test_sockets_msg.h78
1 files changed, 78 insertions, 0 deletions
diff --git a/tests/sockets/test_sockets_msg.h b/tests/sockets/test_sockets_msg.h
new file mode 100644
index 00000000..30094d65
--- /dev/null
+++ b/tests/sockets/test_sockets_msg.h
@@ -0,0 +1,78 @@
+#ifndef __TEST_SOCKETS_MSG_H__
+#define __TEST_SOCKETS_MSG_H__
+
+typedef struct {
+ char *buffer;
+ int length;
+} msg_t;
+
+int do_msg_read(int sockfd, msg_t *msg, int offset, int length, struct sockaddr *addr, socklen_t *addrlen) {
+ int res;
+
+ if (!msg->length) {
+ // read the message length
+ res = recvfrom(sockfd, &msg->length, sizeof(int), 0, (struct sockaddr *)addr, addrlen);
+ if (res == -1) {
+ assert(errno == EAGAIN);
+ return res;
+ }
+ assert(res != 0);
+ msg->buffer = malloc(msg->length);
+
+ printf("do_msg_read: allocating %d bytes for message\n", msg->length);
+ }
+
+ // read the actual message
+ int max = msg->length - offset;
+ if (length && max > length) {
+ max = length;
+ }
+ res = recvfrom(sockfd, msg->buffer + offset, max, 0, (struct sockaddr *)addr, addrlen);
+ if (res == -1) {
+ assert(errno == EAGAIN);
+ return res;
+ }
+
+ printf("do_msg_read: read %d bytes\n", res);
+
+ return res;
+}
+
+int do_msg_write(int sockfd, msg_t *msg, int offset, int length, struct sockaddr *addr, socklen_t addrlen) {
+ int res;
+
+ // send the message length first
+ if (!offset) {
+ if (addr) {
+ res = sendto(sockfd, &msg->length, sizeof(int), 0, addr, addrlen);
+ } else {
+ res = send(sockfd, &msg->length, sizeof(int), 0);
+ }
+ if (res == -1) {
+ assert(errno == EAGAIN);
+ return res;
+ }
+ assert(res == sizeof(int));
+ }
+
+ // then the actual message
+ int max = msg->length - offset;
+ if (length && max > length) {
+ max = length;
+ }
+ if (addr) {
+ res = sendto(sockfd, msg->buffer + offset, max, 0, addr, addrlen);
+ } else {
+ res = send(sockfd, msg->buffer + offset, max, 0);
+ }
+ if (res == -1) {
+ assert(errno == EAGAIN);
+ return res;
+ }
+
+ printf("do_msg_write: wrote %d bytes %d\n", res, msg->length);
+
+ return res;
+}
+
+#endif \ No newline at end of file