tools/hexnet: Implement function for reading bytes from stdin

Soda
BodgeMaster 2022-10-23 01:45:59 +02:00
parent a7e07d2c3c
commit 1d7e98d0b3
1 changed files with 34 additions and 1 deletions

View File

@ -16,6 +16,7 @@
//version 3 along with this program. //version 3 along with this program.
//If not, see https://www.gnu.org/licenses/agpl-3.0.en.html //If not, see https://www.gnu.org/licenses/agpl-3.0.en.html
#include <chrono>
#include <csignal> #include <csignal>
#include <iomanip> #include <iomanip>
#include <iostream> #include <iostream>
@ -70,6 +71,38 @@ in_port_t port;
const uint32_t bufferSize = 2048; const uint32_t bufferSize = 2048;
uint8_t networkBuffer[bufferSize]; 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) { void signalHandler(int signal) {
// shut down gracefully // shut down gracefully
exitProgram = true; exitProgram = true;
@ -148,7 +181,7 @@ int main(int argc, char* argv[]) {
std::vector<CLI::Argument> arguments; std::vector<CLI::Argument> arguments;
arguments.push_back(CLI::Argument("PORT", "the port to lsiten on (or connect to)")); 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) { if (cliParser.getFlag("help").value) {
std::cout << cliParser.getUsage() << std::endl; std::cout << cliParser.getUsage() << std::endl;