summaryrefslogtreecommitdiff
path: root/examples/echo.c
blob: 7790c6a961c20cb5d46a3a0d522c6258fced652f (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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
#if 0 /*
#/  ================================================================
#/
#/    echo.c
#/
#/  ================================================================
#/
#/    Self-compilation shell script
#/
SRC=${0##*./}
BIN=${SRC%.*}
gcc                                         \
  -Wall -Wextra -Werror -pedantic           \
  -Wno-old-style-declaration                \
  -Wno-missing-braces                       \
  -Wno-unused-variable                      \
  -Wno-unused-but-set-variable              \
  -Wno-unused-parameter                     \
  -Wno-overlength-strings                   \
  -O3                                       \
  -fsanitize=undefined,address,leak -mshstk \
  -lX11 -lm                                 \
  -o $BIN $SRC &&                           \
  ./$BIN $@ && rm $BIN
exit $? # */
#endif

#include "../reduced_system_layer.c"

enum {
  MODE_RECV = 1,
  MODE_SEND,

  PORT = 42069,
};

i32 main(i32 argc, c8 **argv) {
  if (argc < 2) {
    if (argc == 1)
      printf("Usade:  %s recv|send\n", argv[0]);
    return -1;
  }

  i32 mode = 0;

  if (strcmp(argv[1], "recv") == 0)
    mode = MODE_RECV;
  else if (strcmp(argv[1], "send") == 0)
    mode = MODE_SEND;

  if (mode == 0) {
    printf("Usage:  %s recv|send\n", argv[0]);
    return -1;
  }

  static c8 buf[256] = "";

  switch (mode) {
    case MODE_RECV: {
      printf("Receiving UDP messages on port %d\n\n", PORT);

      for (;;) {
        i64 n = p_recv(
          0,
          (IP_Address) {
            .protocol   = IPv4_UDP,
            .port       = PORT,
            .v4_address = { 0, 0, 0, 0 },
          },
          sizeof buf - 1,
          (u8 *) buf,
          NULL,
          NULL
        );

        if (strcmp(buf, "!kill") == 0)
          break;

        if (n > 0) {
          buf[n] = '\0';
          printf("%s\n", buf);
        } else
          p_sleep_for(10);
      }
    } break;

    case MODE_SEND: {
      printf("Sending UDP messages to 127.0.0.1 on port %d\nEnter a message or !quit\n\n> ", PORT);

      for (;;) {
        if (scanf("%s", buf) == 0)
          continue;

        if (strcmp(buf, "!quit") == 0)
          break;

        p_send(
          0,
          (IP_Address) {
            .protocol   = IPv4_UDP,
            .port       = PORT,
            .v4_address = { 127, 0, 0, 1 },
          },
          strlen(buf),
          (u8 *) buf,
          NULL
        );

        printf("> ");
      }
    } break;

    default:;
  }

  p_cleanup();
  return 0;
}