From da6461ad47ca909d23abad7803385d2a1d61007d Mon Sep 17 00:00:00 2001 From: BodgeMaster <> Date: Wed, 29 Jan 2025 23:40:28 +0100 Subject: [PATCH] Initial commit, start writing EtherCat --- .gitignore | 1 + README.md | 3 +++ build.sh | 3 +++ ethercat.c | 58 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 65 insertions(+) create mode 100644 .gitignore create mode 100644 README.md create mode 100755 build.sh create mode 100644 ethercat.c diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..de8e66b --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +/ethercat diff --git a/README.md b/README.md new file mode 100644 index 0000000..4946b02 --- /dev/null +++ b/README.md @@ -0,0 +1,3 @@ +# EtherCat + +a tool to interface tap interfaces with stdin and stdout diff --git a/build.sh b/build.sh new file mode 100755 index 0000000..0e7596b --- /dev/null +++ b/build.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +rm ethercat +gcc -Wall -Wextra ethercat.c -o ethercat diff --git a/ethercat.c b/ethercat.c new file mode 100644 index 0000000..c5a550e --- /dev/null +++ b/ethercat.c @@ -0,0 +1,58 @@ +#include +#include +#include +#include +#include +#include +#include +#include + +#define DEVICE_NODE_TUN /dev/net/tun +#define BUFFER_SIZE 0x1000 + +#define EXIT_SUCCESS 0 +#define EXIT_USAGE 1 +#define EXIT_RUNTIME 2 + +int file_descriptor; +char buffer[BUFFER_SIZE]; +struct ifreq ifr; + +int main(int argc, char** argv) { + if (argc != 2) { + fprintf(stderr, "Usage: %s TAP\n", argv[0]); + return EXIT_USAGE; + } else if ((strlen(argv[1])==2 && strncmp(argv[1], "-h", 2)==0) || (strlen(argv[1])==6 &&strncmp(argv[1], "--help", 6))) { + fprintf(stdout, "Usage: %s TAP\n", argv[0]); + return EXIT_SUCCESS; + } + + memset(&ifr, 0, sizeof(ifr)); + ifr.ifr_flags = IFF_TAP | IFF_NO_PI; + strncpy(ifr.ifr_name, argv[1], IFNAMSIZ); + + file_descriptor = open("/dev/net/tun", O_RDWR); + if (file_descriptor == -1) { + fprintf(stderr, "An error occurred while trying to open DEVICE_NODE_TUN: %i\n", errno); + return EXIT_RUNTIME; + } + + if (ioctl(file_descriptor, TUNSETIFF, &ifr) == -1) { + fprintf(stderr, "An error occurred while trying to ioctl: %i\n", errno); + close(file_descriptor); + return EXIT_RUNTIME; + } + + //TODO: + // while input not EOF + // and the tap is still a valid device (it might go away) + // read from tap to stdout + // read from stdin to tap + + //TODO: signal handler for SIGINT (and SIGHUP? maybe others?) + + if (fcntl(fd, F_GETFD) != -1 || errno != EBADF) { + close(file_descriptor); + } + return EXIT_SUCCESS; +}