Instrument Neutral Distributed Interface INDI  2.0.2
tcpsocket_unix.cpp
Go to the documentation of this file.
1 /*
2  Copyright (C) 2022 by Pawel Soja <kernel32.pl@gmail.com>
3 
4  This library is free software; you can redistribute it and/or
5  modify it under the terms of the GNU Lesser General Public
6  License as published by the Free Software Foundation; either
7  version 2.1 of the License, or (at your option) any later version.
8 
9  This library is distributed in the hope that it will be useful,
10  but WITHOUT ANY WARRANTY; without even the implied warranty of
11  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12  Lesser General Public License for more details.
13 
14  You should have received a copy of the GNU Lesser General Public
15  License along with this library; if not, write to the Free Software
16  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
17 */
18 #include "tcpsocket.h"
19 #include "tcpsocket_p.h"
20 
21 #include <sys/un.h>
22 
24 {
25  socketFd = ::socket(domain, SOCK_STREAM, 0);
26  return socketFd >= 0;
27 }
28 
30 {
31  int flags = fcntl(socketFd, F_GETFL, 0);
32  if (flags < 0)
33  {
34  return false;
35  }
36 
37  if (fcntl(socketFd, F_SETFL, flags | O_NONBLOCK) < 0)
38  {
39  return false;
40  }
41 
42  return true;
43 }
44 
45 ssize_t TcpSocketPrivate::recvSocket(void *dst, size_t size)
46 {
47  return ::read(socketFd, dst, size);
48 }
49 
50 ssize_t TcpSocketPrivate::sendSocket(const void *src, size_t size)
51 {
52  return ::write(socketFd, src, size);
53 }
54 
55 SocketAddress SocketAddress::afUnix(const std::string &unixPath)
56 {
57  struct sockaddr_un *sa_un = new struct sockaddr_un;
58 
59  (void)memset(sa_un, 0, sizeof(struct sockaddr_un));
60  sa_un->sun_family = AF_UNIX;
61 
62 #ifdef __linux__
63  // Using abstract socket path to avoid filesystem boilerplate
64  const int offset = 1;
65 #else
66  // Using filesystem socket path
67  const int offset = 0;
68 #endif
69  strncpy(sa_un->sun_path + offset, unixPath.c_str(), sizeof(sa_un->sun_path) - offset - 1);
70 
71  SocketAddress result;
72  result.mData.reset(reinterpret_cast<struct sockaddr *>(sa_un));
73  result.mSize = offsetof(struct sockaddr_un, sun_path) + unixPath.size() + offset;
74  return result;
75 }
std::unique_ptr< struct sockaddr > mData
Definition: tcpsocket_p.h:73
static SocketAddress afUnix(const std::string &hostName)
size_t mSize
Definition: tcpsocket_p.h:74
bool createSocket(int domain)
SocketFileDescriptor socketFd
Definition: tcpsocket_p.h:115
ssize_t sendSocket(const void *src, size_t size)
ssize_t recvSocket(void *dst, size_t size)