Luna/apps/socket-client.cpp
apio 8475a3aad9
All checks were successful
continuous-integration/drone/pr Build is passing
continuous-integration/drone/push Build is passing
socket-client: Send a user-provided message to the server
2023-07-30 11:46:53 +02:00

49 lines
1.1 KiB
C++

#include <os/ArgumentParser.h>
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <unistd.h>
Result<int> luna_main(int argc, char** argv)
{
StringView message;
os::ArgumentParser parser;
parser.add_description("A UNIX domain socket client, to test said sockets.");
parser.add_system_program_info("socket-client"_sv);
parser.add_positional_argument(message, "message"_sv, "exit"_sv);
parser.parse(argc, argv);
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);
}
write(sockfd, message.chars(), message.length());
close(sockfd);
return 0;
}