From 43725ee34adeae4b678d4af918bb6830ee1cb8b8 Mon Sep 17 00:00:00 2001 From: tidwall Date: Fri, 31 May 2024 19:48:14 -0700 Subject: [PATCH] Add port scanner example --- examples/portscan.c | 48 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 examples/portscan.c diff --git a/examples/portscan.c b/examples/portscan.c new file mode 100644 index 0000000..a08973f --- /dev/null +++ b/examples/portscan.c @@ -0,0 +1,48 @@ +// Port scanning +// +// Thanks to @sigidagi for recommending this example. +// See https://github.com/tidwall/neco/issues/14 + +#include +#include +#include "../neco.h" + +void co_dial_port(int argc, void** argv) { + const char *host = argv[0]; // host + int port = *(int*)argv[1]; // port + neco_waitgroup *wg = argv[2]; // waitgroup + + // Dial the port with a one second deadline + char addr[256]; + snprintf(addr, sizeof(addr), "%s:%d", host, port); + int fd = neco_dial_dl("tcp", addr, neco_now() + NECO_SECOND); + if (fd < 0) { + printf("%-5d FAIL\t%s\n", port, neco_strerror(neco_lasterr())); + } else { + printf("%-5d OK\n", port); + close(fd); + } + // Notify the waitgroup that we are done. + neco_waitgroup_done(wg); +} + +int neco_main(int argc, char** argv) { + const char *host = "scanme.nmap.org"; + int ports[] = { 22, 80, 8080, 443 }; + + + // Use a waitgroup to synchronize the coroutines + neco_waitgroup wg; + neco_waitgroup_init(&wg); + + // Dial all the ports + printf("%s\n", host); + for (int i = 0; i < sizeof(ports)/sizeof(int); i++) { + neco_waitgroup_add(&wg, 1); + neco_start(co_dial_port, 3, host, &ports[i], &wg); + } + + // Wait for all coroutines to finish + neco_waitgroup_wait(&wg); + return 0; +} \ No newline at end of file