From 1d7e98d0b3a747ecf172ad5c91a3f978433af8e8 Mon Sep 17 00:00:00 2001 From: BodgeMaster <> Date: Sun, 23 Oct 2022 01:45:59 +0200 Subject: [PATCH] tools/hexnet: Implement function for reading bytes from stdin --- src/tools/hexnet.cpp | 35 ++++++++++++++++++++++++++++++++++- 1 file changed, 34 insertions(+), 1 deletion(-) diff --git a/src/tools/hexnet.cpp b/src/tools/hexnet.cpp index 963668e..e03da34 100644 --- a/src/tools/hexnet.cpp +++ b/src/tools/hexnet.cpp @@ -16,6 +16,7 @@ //version 3 along with this program. //If not, see https://www.gnu.org/licenses/agpl-3.0.en.html +#include #include #include #include @@ -70,6 +71,38 @@ in_port_t port; const uint32_t bufferSize = 2048; uint8_t networkBuffer[bufferSize]; +std::string readByteFromStdin() { + std::string input = ""; + // read 2 characters from stdin + char characterInput; + bool readByte = false; + uint16_t iterationsSinceLastInput = 0; + while (input.length() < 2 && !exitProgram) { + if (std::cin.good()) { + std::cin.get(characterInput); + readByte = true; + } else { + readByte = false; + } + // ignore space, tabs, and newlines + if (readByte && characterInput!=' ' && characterInput!='\n' && characterInput!='\r' && characterInput!='\t') { + input.push_back(characterInput); + } + + iterationsSinceLastInput++; + if (readByte) { + iterationsSinceLastInput = 0; + } + if (iterationsSinceLastInput>1024) { + // prevent integer overflow + iterationsSinceLastInput = 1024; + + std::this_thread::sleep_for(std::chrono::milliseconds(1000)); + } + } + return exitProgram? "" : std::string(1, (char) std::stoi(input, nullptr, 16)); +} + void signalHandler(int signal) { // shut down gracefully exitProgram = true; @@ -148,7 +181,7 @@ int main(int argc, char* argv[]) { std::vector arguments; arguments.push_back(CLI::Argument("PORT", "the port to lsiten on (or connect to)")); - CLI::ArgumentsParser cliParser = CLI::ArgumentsParser(argc, argv, flags, options, arguments, "Arbitrary TCP/UDP connections in hex format", "Note: Make sure your terminal is set up so it doesn't buffer input and, if desired, disable input echoing.\n\tSomething like `stty -echo cbreak` should do but it will also disable some key combinations."); + CLI::ArgumentsParser cliParser = CLI::ArgumentsParser(argc, argv, flags, options, arguments, "Arbitrary TCP/UDP connections in hex format", "Spaces, tabs, newlines, and carriage returns in the input are ignored.\n\tYou may want to disable input echoing using `stty -echo` (reenable using `stty echo`).\n\tNote that many terminals do line buffering on the input by default."); if (cliParser.getFlag("help").value) { std::cout << cliParser.getUsage() << std::endl;