simple-socket library 1.5.0
Loading...
Searching...
No Matches
SockAddress.h
1#ifndef NET_SockAddress_h__
2#define NET_SockAddress_h__
3
4#include "SimpleSocket.h"
5
6#include <cstddef>
7#include <cstring>
8#include <string>
9
10#include <sys/socket.h>
11
12namespace NET
13{
14 class SockAddress
15 {
16 public:
17 SockAddress() noexcept = default;
18
19 // Numeric IPv4 or IPv6 address
20 SockAddress( AddressFamily family, std::string_view address, unsigned short port);
21
22 // Wildcard address: 0.0.0.0 or ::
23 SockAddress( AddressFamily family, unsigned short port);
24
25 // Unix filesystem pathname
26 explicit SockAddress( std::string_view path);
27
28 sockaddr* data() noexcept;
29 const sockaddr* data() const noexcept;
30 socklen_t length() const noexcept;
31
32 sa_family_t family() const noexcept;
33 bool empty() const noexcept;
34
35 // For getsockname(), getpeername(), recvfrom(), etc.
36 // Resets internal state to accept new data from syscall
37 socklen_t* lengthPtr() noexcept;
38
39 // Valid for AF_INET / AF_INET6
40 unsigned short port() const noexcept;
41
42 std::string address() const;
43
44 static sa_family_t nativeFamily(AddressFamily family) noexcept;
45
46 private:
47 template<typename T>
48 void store(const T& address, socklen_t length) noexcept
49 {
50 static_assert(sizeof(T) <= sizeof(sockaddr_storage));
51 static_assert(alignof(T) <= alignof(sockaddr_storage));
52
53 m_storage = {};
54 std::memcpy( &m_storage, &address, sizeof(address));
55 m_length = length;
56 }
57
58 sockaddr_storage m_storage{};
59 socklen_t m_length = sizeof(m_storage);
60 };
61
62} // namespace NET
63
64#endif // NET_SockAddress_h__