From d82cf253bd92bcb6edc88e7b954f6ffdeea17d0c Mon Sep 17 00:00:00 2001 From: damage Date: Sun, 21 Jan 2024 11:30:59 +0100 Subject: [PATCH] generic command and Makefile --- Makefile | 13 +++++++++ command.c | 83 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 96 insertions(+) create mode 100644 Makefile create mode 100644 command.c diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..dd52620 --- /dev/null +++ b/Makefile @@ -0,0 +1,13 @@ +BIN=bin + +all: dirs command + +command: command.c + gcc -o ${BIN}/command command.c + +.PHONY: clean dirs +clean: + rm -rf ${BIN} + +dirs: + mkdir -p ${BIN} diff --git a/command.c b/command.c new file mode 100644 index 0000000..4a96012 --- /dev/null +++ b/command.c @@ -0,0 +1,83 @@ +#include +#include +#include + +#include +#include // BSD compatible +#include +#include + +#include +#include + +#define SERVER "::1" +#define PORT 49000 + +#define COMMAND_BUFFER 256 + +char* printable(char *str) { + char *ret = strdup(str); + + for (int i = strlen(ret); i >= 0; i--) { + if (ret[i] == '\r' || ret[i] == '\n') { + ret[i] = '\0'; + } + } + + return ret; +} + +void sendCommand(int sock, char *cmd) { + char bytesToSend[COMMAND_BUFFER]; + memset(bytesToSend, 0, COMMAND_BUFFER); + + strcpy(&bytesToSend[0], "CMND"); + strcpy(&bytesToSend[5], cmd); + + int numBytesSend = send(sock, bytesToSend, 5 + strlen(cmd), 0); + if (numBytesSend >= 0) { + //printf("Send %d bytes to %s:%d: %s\n", numBytesSend, SERVER, PORT, printable(bytesToSend)); + } else { + fprintf(stderr, "Failed to send message to %s:%d (%d): %s", SERVER, PORT, errno, strerror(errno)); + exit(EXIT_FAILURE); + } +} + +int main(int argc, char *argv[]) { + int xplaneSocket; + struct sockaddr_in6 xplaneAddress; + + int err; + + // check argument + if (argc != 2) { + fprintf(stderr, "Usage: %s \n", argv[0]); + exit(EXIT_FAILURE); + } + + // create socket + xplaneSocket = socket(AF_INET6, SOCK_DGRAM, 0); + if (xplaneSocket == -1) { + fprintf(stderr, "Error creating socket (%d): %s\n", errno, strerror(errno)); + exit(EXIT_FAILURE); + } + + // prepare address struct + xplaneAddress.sin6_family = AF_INET6; + xplaneAddress.sin6_port = htons(PORT); + inet_pton(AF_INET6, SERVER, &xplaneAddress.sin6_addr.s6_addr); + + // connect to xplane + err = connect(xplaneSocket, (struct sockaddr *)&xplaneAddress, sizeof(xplaneAddress)); + if (err) { + fprintf(stderr, "Error connecting %s:%d (%d): %s\n", SERVER, PORT, err, gai_strerror(err)); + exit(EXIT_FAILURE); + } + + // send payload + sendCommand(xplaneSocket, argv[1]); + + // bye bye (and no, I don't care about error anymore; I'll exit anyway?!) + close(xplaneSocket); + exit(EXIT_SUCCESS); +}