simple-socket library 1.2.0
UnixDatagramSocket.cpp
Go to the documentation of this file.
2#include "TempFailure.h"
3
4#include <sys/socket.h>
5#include <sys/un.h>
6#include <poll.h>
7
8using namespace NET;
9
13
14void UnixDatagramSocket::sendTo( const void* buffer, size_t len, std::string_view foreignPath)
15{
16 sockaddr_un destAddr;
17 fillAddress( foreignPath, destAddr);
18
19 int sent = TEMP_FAILURE_RETRY (::sendto( m_socket, (const raw_type*)buffer, len, 0, (sockaddr*)&destAddr, sizeof(destAddr)));
20
21 // Write out the whole buffer as a single message
22 if( sent != (int)len)
23 throw SocketException("Send failed (sendto)");
24}
25
26int UnixDatagramSocket::receiveFrom( void* buffer, size_t len, std::string& sourcePath)
27{
28 sockaddr_un clientAddr;
29 socklen_t addr_len = sizeof(clientAddr);
30
31 int ret = TEMP_FAILURE_RETRY (::recvfrom( m_socket, (raw_type*)buffer, len, 0, (sockaddr*)&clientAddr, &addr_len));
32 if( ret < 0)
33 throw SocketException("Receive failed (recvfrom)");
34
35 sourcePath = extractPath( clientAddr, addr_len);
36 return ret;
37}
38
39int UnixDatagramSocket::timedReceiveFrom( void* buffer, size_t len, std::string& sourcePath, int timeout)
40{
41 struct pollfd poll;
42 poll.fd = m_socket;
43 poll.events = POLLIN | POLLPRI | POLLRDHUP;
44
45 int ret = TEMP_FAILURE_RETRY (::poll( &poll, 1, timeout));
46
47 if( ret == 0) return 0;
48 if( ret < 0) throw SocketException("Receive failed (poll)");
49
50 if( poll.revents & POLLRDHUP)
51 m_peerDisconnected = true;
52
53 if( poll.revents & POLLIN || poll.revents & POLLPRI)
54 return receiveFrom( buffer, len, sourcePath);
55
56 return 0;
57}
static const int len
#define TEMP_FAILURE_RETRY(expression)
Definition TempFailure.h:8
Definition CANFrame.h:7
Signals a problem with the execution of a socket call.
void sendTo(const void *buffer, size_t len, std::string_view foreignPath)
int timedReceiveFrom(void *buffer, size_t len, std::string &sourcePath, int timeout)
int receiveFrom(void *buffer, size_t len, std::string &sourcePath)
static std::string extractPath(const sockaddr_un &addr, socklen_t len)
extracts a path string from the socket address structure
static void fillAddress(std::string_view path, sockaddr_un &addr)
UnixSocket(int type, int protocol)
allows a subclass to create new socket