-
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathClient.mpp
More file actions
51 lines (42 loc) · 1.41 KB
/
Client.mpp
File metadata and controls
51 lines (42 loc) · 1.41 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
module;
#include <CppUtils/System/OS.hpp>
#if defined(OS_WINDOWS)
# include <winsock2.h>
#elif defined(OS_LINUX) or defined(OS_MACOS)
# include <sys/socket.h>
# include <cerrno>
#endif
export module CppUtils.Network.Client;
import std;
export import CppUtils.Network.Socket;
export namespace CppUtils::Network
{
class Client final: public Socket
{
public:
explicit inline Client(Domain domain = Domain::IPV4, Type type = Type::TCP):
Socket{domain, type}
{}
[[nodiscard]] inline auto connect(std::string_view ip, std::uint16_t port) -> std::expected<void, std::error_code>
{
if (const auto detectedDomain = ip.find(':') != std::string_view::npos ? Domain::IPV6 : Domain::IPV4;
detectedDomain != getDomain())
*this = Client{detectedDomain, getType()};
auto address = makeAddress(std::empty(ip) ? "127.0.0.1" : ip, port);
if (address.length == 0)
return std::unexpected{std::make_error_code(std::errc::invalid_argument)};
if (not isValid())
return std::unexpected{std::make_error_code(std::errc::bad_file_descriptor)};
if (::connect(nativeHandle(), reinterpret_cast<sockaddr*>(std::addressof(address.storage)), address.length) < 0)
{
#if defined(OS_WINDOWS)
if (WSAGetLastError() != WSAEWOULDBLOCK)
#elif defined(OS_LINUX) or defined(OS_MACOS)
if (errno != EINPROGRESS)
#endif
return std::unexpected{std::error_code(errno, std::generic_category())};
}
return {};
}
};
}