]> granicus.if.org Git - icinga2/blob - lib/base/socket.hpp
Merge pull request #7185 from Icinga/bugfix/gelfwriter-wrong-log-facility
[icinga2] / lib / base / socket.hpp
1 /* Icinga 2 | (c) 2012 Icinga GmbH | GPLv2+ */
2
3 #ifndef SOCKET_H
4 #define SOCKET_H
5
6 #include "base/i2-base.hpp"
7 #include "base/object.hpp"
8 #include <boost/thread/mutex.hpp>
9
10 namespace icinga
11 {
12
13 /**
14  * Base class for connection-oriented sockets.
15  *
16  * @ingroup base
17  */
18 class Socket : public Object
19 {
20 public:
21         DECLARE_PTR_TYPEDEFS(Socket);
22
23         Socket() = default;
24         Socket(SOCKET fd);
25         ~Socket() override;
26
27         SOCKET GetFD() const;
28
29         void Close();
30
31         std::pair<String, String> GetClientAddressDetails();
32         String GetClientAddress();
33         std::pair<String, String> GetPeerAddressDetails();
34         String GetPeerAddress();
35
36         size_t Read(void *buffer, size_t size);
37         size_t Write(const void *buffer, size_t size);
38
39         void Listen();
40         Socket::Ptr Accept();
41
42         bool Poll(bool read, bool write, struct timeval *timeout = nullptr);
43
44         void MakeNonBlocking();
45
46         static void SocketPair(SOCKET s[2]);
47
48 protected:
49         void SetFD(SOCKET fd);
50
51         int GetError() const;
52
53         mutable boost::mutex m_SocketMutex;
54
55 private:
56         SOCKET m_FD{INVALID_SOCKET}; /**< The socket descriptor. */
57
58         static std::pair<String, String> GetDetailsFromSockaddr(sockaddr *address, socklen_t len);
59         static String GetHumanReadableAddress(const std::pair<String, String>& socketDetails);
60 };
61
62 class socket_error : virtual public std::exception, virtual public boost::exception { };
63
64 }
65
66 #endif /* SOCKET_H */