Luna/apps/socket-client.cpp

49 lines
1.1 KiB
C++
Raw Normal View History

#include <os/ArgumentParser.h>
2023-07-28 15:31:27 +00:00
#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)
2023-07-28 15:31:27 +00:00
{
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);
2023-07-28 15:31:27 +00:00
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());
2023-07-28 15:31:27 +00:00
close(sockfd);
return 0;
}