lib45d
45Drives C++ Library Development Documentation
UnixSocketClient.hpp
1 // -*- C++ -*-
2 /*
3  * Copyright (C) 2021 Joshua Boudreau <jboudreau@45drives.com>
4  *
5  * This file is part of lib45d.
6  *
7  * lib45d is free software: you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation, either version 3 of the License, or
10  * (at your option) any later version.
11  *
12  * lib45d is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with lib45d. If not, see <https://www.gnu.org/licenses/>.
19  */
20 
21 #pragma once
22 
23 #include <45d/socket/SocketBase.hpp>
24 
25 extern "C" {
26 #include <sys/un.h>
27 }
28 
29 namespace ffd {
34  class UnixSocketClient : public SocketBase {
35  public:
41  UnixSocketClient(const std::string &path) : SocketBase(AF_UNIX, SOCK_STREAM) {
42  memset(&server_addr_, 0, sizeof(server_addr_));
43  server_addr_.sun_family = AF_UNIX;
44  if (path.length() >= sizeof(server_addr_.sun_path))
45  throw SocketAddressException("Socket address too long", ENAMETOOLONG);
46  strncpy(server_addr_.sun_path, path.c_str(), sizeof(server_addr_.sun_path) - 1);
47  io_fd_ = fd_;
48  }
54  int connect() {
55  int res = ::connect(fd_, (sockaddr *)&server_addr_, sizeof(server_addr_));
56  if (res == -1) {
57  int error = errno;
58  throw SocketConnectException(strerror(error), error);
59  }
60  return io_fd_;
61  }
62  private:
63  struct sockaddr_un server_addr_;
64  };
65 } // namespace ffd
ffd::SocketBase::io_fd_
int io_fd_
Connection fd.
Definition: SocketBase.hpp:278
ffd::UnixSocketClient
Unix Socket Client class. Used for IPC through a named socket inode.
Definition: UnixSocketClient.hpp:34
ffd::UnixSocketClient::server_addr_
struct sockaddr_un server_addr_
Unix socket address struct.
Definition: UnixSocketClient.hpp:63
ffd::UnixSocketClient::UnixSocketClient
UnixSocketClient(const std::string &path)
Construct a new Unix Socket Client object.
Definition: UnixSocketClient.hpp:41
ffd::SocketAddressException
Thrown when the socket address is too long.
Definition: Exceptions.hpp:57
ffd
45Drives namespace
Definition: Bytes.hpp:27
ffd::SocketBase
Base Unix Socket Class for opening and closing the socket.
Definition: SocketBase.hpp:57
ffd::SocketBase::fd_
int fd_
File descriptor of socket.
Definition: SocketBase.hpp:277
ffd::UnixSocketClient::connect
int connect()
Make connection to socket.
Definition: UnixSocketClient.hpp:54
ffd::SocketConnectException
Thrown when connect() fails.
Definition: Exceptions.hpp:89