fnet.c

Simple C networking library
git clone git://git.finwo.net/lib/fnet.c
Log | Files | Refs | README

commit 21137b3520935e58ecfc7d908f984b08b72e37df
parent b3c8ca014e7837fe0df52e28d9c041b277033d28
Author: Yersa Nordman <yersa@finwo.nl>
Date:   Tue,  1 Aug 2023 23:45:54 +0200

Made port and address dynamic in test program

Diffstat:
Mtest.c | 86+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----------
1 file changed, 75 insertions(+), 11 deletions(-)

diff --git a/test.c b/test.c @@ -1,5 +1,6 @@ #include <stdint.h> #include <stdio.h> +#include <string.h> #include <unistd.h> #include "fnet.h" @@ -21,18 +22,81 @@ void onConnect(struct fnet_ev *ev) { ev->connection->onClose = onClose; } -int main() { - const struct fnet_options_t opts = { - .proto = FNET_PROTO_TCP, - .flags = 0, - .onConnect = onConnect, - .onData = NULL, - .onClose = NULL, - .udata = NULL, - }; +int main(int argc, const char *argv[]) { + int i, n; - fnet_listen("0.0.0.0", 1337, &opts); - fnet_main(); + const char *addr = "127.0.0.1"; + uint16_t port = 1337; + int mode = 1; // 1 = listen, 2 = connect + for( i = 0 ; i < argc ; i++ ) { + + if ( + (!strcmp("--address", argv[i])) || + (!strcmp("-a", argv[i])) + ) { + i++; + addr = argv[i]; + continue; + } + + if ( + (!strcmp("--port", argv[i])) || + (!strcmp("-p", argv[i])) + ) { + i++; + n = atoi(argv[i]); + // Must be positive, 0 = not allowed, see TCP spec + if (n <= 0) { + fprintf(stderr, "%s: Port must be above 1, got %d\n", argv[0], n); + return 1; + } + // Don't allow dynamic ports + if (n >= 49152) { + fprintf(stderr, "%s: Port must be below 49152, got %d\n", argv[0], n); + return 1; + } + port = n; + continue; + } + + if ( + (!strcmp("--listen", argv[i])) || + (!strcmp("-l", argv[i])) + ) { + mode = 1; + continue; + } + + if ( + (!strcmp("--connect", argv[i])) || + (!strcmp("-c", argv[i])) + ) { + mode = 2; + continue; + } + + printf("Arg: %s\n", argv[i]); + } + + printf("Address: %s\n", addr); + printf("Port : %d\n", port); + + + if (mode == 1) { + const struct fnet_options_t opts = { + .proto = FNET_PROTO_TCP, + .flags = 0, + .onConnect = onConnect, + .onData = NULL, + .onClose = NULL, + .udata = &mode, + }; + fnet_listen(addr, port, &opts); + fnet_main(); + return 0; + } + + fprintf(stderr, "Mode not implemented\n"); return 42; }