Nix (Dev) 3.5.10
dev - 3.5.10 - 1af9301
Loading...
Searching...
No Matches
address.hpp
Go to the documentation of this file.
1#ifndef IV_SRC_COMMS_SOCKET_ADDRESS_HPP_
2#define IV_SRC_COMMS_SOCKET_ADDRESS_HPP_
3
4#include <memory>
5#include <string>
6#include <string_view>
7#include <stdexcept>
8#include <sys/socket.h>
9#include <arpa/inet.h>
10
12{
13template <typename T>
14class SocketAddress
15{
16protected:
17 std::unique_ptr<T> m_sockaddr;
18 sa_family_t m_family;
19 std::string m_address;
20 uint16_t m_port;
21
22public:
23 SocketAddress(std::string_view address, uint16_t port)
24 {
25 m_sockaddr = std::make_unique<T>();
26 m_address = address;
27 m_port = port;
28
29 if constexpr (std::is_same<T, sockaddr_in>::value)
30 {
31 m_sockaddr->sin_family = AF_INET;
32 m_sockaddr->sin_port = htons(port);
33 if (inet_pton(AF_INET, address, &m_sockaddr->sin_addr) <= 0)
34 {
35 throw std::runtime_error("Invalid address");
36 }
37 }
38 else if constexpr (std::is_same<T, sockaddr_in6>::value)
39 {
40 m_sockaddr->sin6_family = AF_INET6;
41 m_sockaddr->sin6_port = htons(port);
42 if (inet_pton(AF_INET6, address, &m_sockaddr->sin6_addr) <= 0)
43 {
44 throw std::runtime_error("Invalid address");
45 }
46 }
47 else
48 {
49 throw std::runtime_error("Invalid address family");
50 }
51 }
52
53 ~SocketAddress() = default;
54
55
56 sockaddr *getSocketAddress() const
57 {
58 return reinterpret_cast<sockaddr *>(m_sockaddr.get());
59 }
60
61 std::string getAddress() const
62 {
63 return m_address;
64 }
65
66 uint16_t getPort() const
67 {
68 return m_port;
69 }
70
71 socklen_t size() const
72 {
73 return sizeof(*m_sockaddr);
74 }
75
76 sa_family_t getFamily() const
77 {
78 return m_family;
79 }
80
81};
82
85
86}
87
88
89#endif//IV_SRC_COMMS_SOCKET_ADDRESS_HPP_
Definition CSocketAddress.hpp:18
std::string getAddress() const
Definition address.hpp:61
uint16_t getPort() const
Definition address.hpp:66
socklen_t size() const
Definition address.hpp:71
SocketAddress(std::string_view address, uint16_t port)
Definition address.hpp:23
std::unique_ptr< T > m_sockaddr
Definition address.hpp:17
sockaddr * getSocketAddress() const
Definition address.hpp:56
sa_family_t getFamily() const
Definition address.hpp:76
std::string m_address
Definition address.hpp:19
sa_family_t m_family
Definition address.hpp:18
uint16_t m_port
Definition address.hpp:20
Definition address.hpp:12