aboutsummaryrefslogtreecommitdiff
path: root/tests/sockets/test_sockets_msg.h
blob: 0e68803cfb53adf15b1c4b2044522920b275a2dc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
#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);

    printf("do_msg_read: allocating %d bytes for message\n", msg->length);

    msg->buffer = malloc(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;
    }
    printf("do_msg_write: sending message header for %d bytes\n", msg->length);
    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