]> git.tdb.fi Git - libs/net.git/blob - source/net/unix.cpp
9d8cf2780af0da1d99eb177136944b30659730bb
[libs/net.git] / source / net / unix.cpp
1 #include <stdexcept>
2 #ifndef _WIN32
3 #include <sys/un.h>
4 #endif
5 #include "sockaddr_private.h"
6 #include "unix.h"
7
8 using namespace std;
9
10 namespace Msp {
11 namespace Net {
12
13 UnixAddr::UnixAddr():
14         abstract(false)
15 {
16 #ifdef _WIN32
17         throw logic_error("no unix sockets on windows");
18 #endif
19 }
20
21 UnixAddr::UnixAddr(const SysAddr &sa):
22         abstract(false)
23 {
24 #ifdef _WIN32
25         (void)sa;
26         throw logic_error("no unix sockets on windows");
27 #else
28         const sockaddr_un &sau = reinterpret_cast<const sockaddr_un &>(sa.addr);
29         if(static_cast<size_t>(sa.size)>sizeof(sa_family_t))
30         {
31                 abstract = (sau.sun_path[0]==0);
32                 path.assign(sau.sun_path+abstract, sa.size-sizeof(sa_family_t)-abstract);
33         }
34 #endif
35 }
36
37 UnixAddr::UnixAddr(const string &p, bool a):
38         path(p),
39         abstract(a)
40 {
41 #ifdef _WIN32
42         throw logic_error("no unix sockets on windows");
43 #else
44         if(sizeof(sa_family_t)+path.size()+1>sizeof(sockaddr_storage))
45                 throw invalid_argument("UnixAddr");
46 #endif
47 }
48
49 SockAddr::SysAddr UnixAddr::to_sys() const
50 {
51         SysAddr sa;
52 #ifndef _WIN32
53         sa.size = sizeof(sa_family_t);
54         if(!path.empty())
55                 sa.size += path.size()+1;
56
57         sockaddr_un &sau = reinterpret_cast<sockaddr_un &>(sa.addr);
58         sau.sun_family = AF_UNIX;
59         if(!path.empty())
60         {
61                 if(abstract)
62                         sau.sun_path[0] = 0;
63                 std::copy(path.begin(), path.end(), sau.sun_path+abstract);
64                 if(!abstract)
65                         sau.sun_path[path.size()] = 0;
66         }
67 #endif
68
69         return sa;
70 }
71
72 string UnixAddr::str() const
73 {
74         string result = "unix:";
75         if(abstract)
76                 result += '@';
77         result += path;
78         return result;
79 }
80
81 } // namespace Net
82 } // namespace Msp