-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathUnixSocket.cpp
More file actions
70 lines (54 loc) · 1.74 KB
/
Copy pathUnixSocket.cpp
File metadata and controls
70 lines (54 loc) · 1.74 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#include "UnixSocket.h"
#include <sys/socket.h>
#include <sys/un.h>
#include <unistd.h>
#include <cstring>
using namespace NET;
UnixSocket::UnixSocket( int type, int protocol)
: SimpleSocket( UNIX, type, protocol)
{}
void UnixSocket::connect( std::string_view foreignPath)
{
sockaddr_un addr;
fillAddress( foreignPath, addr);
if( ::connect( m_socket, (sockaddr*) &addr, sizeof(addr)) < 0)
throw SocketException("Connect failed (connect)");
}
void UnixSocket::bind( std::string_view localPath)
{
sockaddr_un addr;
fillAddress( localPath, addr);
::unlink( addr.sun_path);
if( ::bind( m_socket, (sockaddr*) &addr, sizeof(addr)) < 0)
throw SocketException("Set of local path failed (bind)");
}
std::string UnixSocket::getLocalPath() const
{
sockaddr_un addr;
socklen_t addr_len = sizeof(addr);
if( getsockname( m_socket, (sockaddr*) &addr, &addr_len) < 0)
throw SocketException("Fetch of local path failed (getsockname)");
return extractPath( addr, addr_len);
}
std::string UnixSocket::getForeignPath() const
{
sockaddr_un addr;
socklen_t addr_len = sizeof(addr);
if( getpeername( m_socket, (sockaddr*) &addr, &addr_len) < 0)
throw SocketException("Fetch of foreign path failed (getpeername)");
return extractPath( addr, addr_len);
}
void UnixSocket::fillAddress( std::string_view path, sockaddr_un& addr)
{
const int len = path.length();
// needed space is size plus null character
if( len >= sizeof(sockaddr_un::sun_path)-1)
throw SocketException("Path to socket file is too long", false);
addr.sun_family = AF_LOCAL;
std::memcpy( addr.sun_path, path.data(), len);
addr.sun_path[len] = 0;
}
std::string UnixSocket::extractPath( const sockaddr_un& addr, socklen_t len)
{
return std::string( addr.sun_path, len - sizeof(sa_family_t) - 1);
}