1 // Copyright Leandro Lucarella 2008 - 2010.
2 // Distributed under the Boost Software License, Version 1.0.
3 // (See accompanying file COPYING or copy at
4 // http://www.boost.org/LICENSE_1_0.txt)
7 #ifndef POSIXX_SOCKET_UNIX_HPP_
8 #define POSIXX_SOCKET_UNIX_HPP_
10 #include "basic_socket.hpp" // posixx::socket
12 #include <sys/un.h> // sockaddr_un
13 #include <string> // std::string
14 #include <utility> // std::pair
15 #include <cstring> // memset, memcpy, memcmp
19 namespace posixx { namespace socket {
21 /// Unix (local) sockets
24 /// Unix socket address
25 struct sockaddr: sockaddr_un
28 /// Create an empty unix socket address.
32 * Create a unix socket address.
34 * @param path Path to the socket (should be less than ::PATH_MAX
37 sockaddr(const std::string& path) throw (std::logic_error);
39 /// Length of this unix socket address
40 socklen_t length() const throw ();
42 /// Get the path of this unix socket address
43 std::string path() const throw ();
45 /// Compare two unix socket addresses
46 bool operator == (const sockaddr& other) const throw ();
50 /// Unix socket traits
53 /// Socket address type.
54 typedef posixx::socket::unix::sockaddr sockaddr;
56 enum { PF = PF_UNIX };
60 typedef posixx::socket::basic_socket< traits > socket;
62 /// Pair of unix sockets
63 typedef std::pair< socket*, socket* > pair_type;
65 /// Create a pair of connected unix sockets
66 pair_type pair(type type, int protocol = 0) throw (posixx::error);
68 } } } // namespace posixx::socket::unix
73 posixx::socket::unix::sockaddr::sockaddr() throw ()
79 posixx::socket::unix::sockaddr::sockaddr(const std::string& path)
80 throw (std::logic_error)
82 if (path.size() >= sizeof(sun_path))
83 throw std::logic_error("path too long");
85 memcpy(sun_path, path.c_str(), path.size() + 1); // \0
89 socklen_t posixx::socket::unix::sockaddr::length() const throw ()
91 return sizeof(sun_family) + strlen(sun_path);
95 std::string posixx::socket::unix::sockaddr::path() const throw ()
97 return std::string(sun_path);
101 bool posixx::socket::unix::sockaddr::operator == (const sockaddr& other)
104 return sun_family == other.sun_family
105 && !strncmp(sun_path, other.sun_path, sizeof(sun_path));
109 posixx::socket::unix::pair_type posixx::socket::unix::pair(type type,
110 int protocol) throw (posixx::error)
112 return posixx::socket::pair< socket >(type, protocol);
115 #endif // POSIXX_SOCKET_UNIX_HPP_