From 211f14452126797ca9efc341797fde1f2d171fb8 Mon Sep 17 00:00:00 2001 From: Sanyam Suhas Mulay Date: Tue, 20 Jan 2026 14:42:06 +0530 Subject: [PATCH] added sample test files in python and c++ for linux socket testing --- linux_socket_test.cpp | 63 +++++++++++++++++++++++++++++++++++++++++++ linux_socket_test.py | 25 +++++++++++++++++ requirements.txt | 0 3 files changed, 88 insertions(+) create mode 100644 linux_socket_test.cpp create mode 100644 linux_socket_test.py create mode 100644 requirements.txt diff --git a/linux_socket_test.cpp b/linux_socket_test.cpp new file mode 100644 index 0000000..8a98e0c --- /dev/null +++ b/linux_socket_test.cpp @@ -0,0 +1,63 @@ +#include +#include +#include +#include +#include +#include +#include + +#define SOCKET_FILE "/tmp/mysocket" + +// WARNING: UNTESTED + +int main() { + int server_fd, client_fd; + struct sockaddr_un addr; + char buf[1024]; + ssize_t num_read; + + // Remove any previous socket file + unlink(SOCKET_FILE); + + server_fd = socket(AF_UNIX, SOCK_STREAM, 0); + if (server_fd == -1) { + perror("socket"); + exit(EXIT_FAILURE); + } + + memset(&addr, 0, sizeof(struct sockaddr_un)); + addr.sun_family = AF_UNIX; + strncpy(addr.sun_path, SOCKET_FILE, sizeof(addr.sun_path) - 1); + + if (bind(server_fd, (struct sockaddr *)&addr, sizeof(struct sockaddr_un)) == -1) { + perror("bind"); + exit(EXIT_FAILURE); + } + + if (listen(server_fd, 5) == -1) { + perror("listen"); + exit(EXIT_FAILURE); + } + + std::cout << "Listening on " << SOCKET_FILE << "..." << std::endl; + + while (true) { + client_fd = accept(server_fd, NULL, NULL); + if (client_fd == -1) { + perror("accept"); + continue; + } + + num_read = read(client_fd, buf, sizeof(buf) - 1); + if (num_read > 0) { + buf[num_read] = '\0'; + std::cout << "Received: " << buf << std::endl; + write(client_fd, buf, num_read); // Echo back + } + close(client_fd); + } + + close(server_fd); + unlink(SOCKET_FILE); + return 0; +} diff --git a/linux_socket_test.py b/linux_socket_test.py new file mode 100644 index 0000000..fc00356 --- /dev/null +++ b/linux_socket_test.py @@ -0,0 +1,25 @@ +import socket +import os + +SOCKET_FILE = '/tmp/mysocket' + +if os.path.exists(SOCKET_FILE): + os.remove(SOCKET_FILE) + +server = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) +server.bind(SOCKET_FILE) +server.listen(1) + +print(f"Listening on {SOCKET_FILE}...") + +try: + while True: + conn, _ = server.accept() + data = conn.recv(1024) + if data: + print("Received:", data.decode()) + conn.sendall(data) # Echo back + conn.close() +finally: + server.close() + os.remove(SOCKET_FILE) diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..e69de29