diff --git a/apps/CMakeLists.txt b/apps/CMakeLists.txt index a892f745..2b86ec4a 100644 --- a/apps/CMakeLists.txt +++ b/apps/CMakeLists.txt @@ -43,3 +43,4 @@ luna_app(kill.cpp kill) luna_app(gol.cpp gol) luna_app(buffer-test.cpp buffer-test) luna_app(socket-test.cpp socket-test) +luna_app(socket-client.cpp socket-client) diff --git a/apps/socket-client.cpp b/apps/socket-client.cpp new file mode 100644 index 00000000..67d2f3d2 --- /dev/null +++ b/apps/socket-client.cpp @@ -0,0 +1,40 @@ +#include +#include +#include +#include +#include + +int main() +{ + int sockfd = socket(AF_UNIX, SOCK_STREAM, 0); + if (sockfd < 0) + { + perror("socket"); + return 0; + } + + struct sockaddr_un un; + un.sun_family = AF_UNIX; + strncpy(un.sun_path, "/tmp/local.sock", sizeof(un.sun_path)); + + if (connect(sockfd, (struct sockaddr*)&un, sizeof(un)) < 0) + { + perror("connect"); + return 1; + } + + char buf[4096]; + ssize_t nread = read(sockfd, buf, sizeof(buf) - 1); + if (nread > 0) + { + buf[nread] = 0; + printf("Message from server: %s\n", buf); + } + + const char* message = "EXIT"; + write(sockfd, message, strlen(message)); + + close(sockfd); + + return 0; +} diff --git a/apps/socket-test.cpp b/apps/socket-test.cpp index 3907ec3c..b4279c17 100644 --- a/apps/socket-test.cpp +++ b/apps/socket-test.cpp @@ -1,10 +1,18 @@ +#include #include #include #include +#include #include +#include int main() { + setgid(1000); + setuid(1000); + + remove("/tmp/local.sock"); + int sockfd = socket(AF_UNIX, SOCK_STREAM, 0); if (sockfd < 0) { @@ -21,4 +29,47 @@ int main() perror("bind"); return 1; } + + if (listen(sockfd, 10) < 0) + { + perror("listen"); + return 1; + } + + while (1) + { + int fd = accept(sockfd, NULL, NULL); + if (fd < 0) + { + perror("accept"); + return 1; + } + + puts("New connection from client, sending hello"); + + const char* message = "Hello, client!"; + write(fd, message, strlen(message)); + + puts("Now waiting for client to message back"); + + char buf[4096]; + ssize_t nread = read(fd, buf, sizeof(buf) - 1); + if (nread >= 0) + { + buf[nread] = 0; + printf("Message from client: %s\n", buf); + if (!strcasecmp(buf, "exit")) + { + close(fd); + close(sockfd); + remove("/tmp/local.sock"); + return 0; + } + } + else { printf("Error reading from client: %s\n", strerror(errno)); } + + puts("Transmission ended, closing connection"); + + close(fd); + } } diff --git a/base/etc/init/98-listen b/base/etc/init/98-listen new file mode 100644 index 00000000..a27cf204 --- /dev/null +++ b/base/etc/init/98-listen @@ -0,0 +1,6 @@ +Name=listen +Description=Start a Unix domain socket test server. +Command=/usr/bin/socket-test +StandardOutput=/dev/uart0 +StandardError=/dev/uart0 +Restart=true