-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSocket.cpp
More file actions
1459 lines (1197 loc) · 44 KB
/
Socket.cpp
File metadata and controls
1459 lines (1197 loc) · 44 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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "jsocketpp/Socket.hpp"
#include "jsocketpp/internal/ScopedBlockingMode.hpp"
#include "jsocketpp/SocketTimeoutException.hpp"
#include <chrono>
#include <cstring> // std::memcpy
#include <span>
using namespace jsocketpp;
Socket::Socket(const SOCKET client, const sockaddr_storage& addr, const socklen_t len, const std::size_t recvBufferSize,
const std::size_t sendBufferSize, const std::size_t internalBufferSize, const int soRecvTimeoutMillis,
const int soSendTimeoutMillis, const bool tcpNoDelay, const bool keepAlive, const bool nonBlocking)
: SocketOptions(client), _remoteAddr(addr), _remoteAddrLen(len), _internalBuffer(internalBufferSize)
{
if (getSocketFd() == INVALID_SOCKET)
throw SocketException("Socket(SOCKET): invalid socket descriptor.");
try
{
setReceiveBufferSize(recvBufferSize);
setSendBufferSize(sendBufferSize);
setInternalBufferSize(internalBufferSize);
setTcpNoDelay(tcpNoDelay);
setKeepAlive(keepAlive);
setNonBlocking(nonBlocking);
if (soRecvTimeoutMillis >= 0)
setSoRecvTimeout(soRecvTimeoutMillis);
if (soSendTimeoutMillis >= 0)
setSoSendTimeout(soSendTimeoutMillis);
}
catch (const SocketException&)
{
cleanupAndRethrow();
}
}
Socket::Socket(const std::string_view host, const Port port, const std::optional<std::size_t> recvBufferSize,
const std::optional<std::size_t> sendBufferSize, const std::optional<std::size_t> internalBufferSize,
const bool reuseAddress, const int soRecvTimeoutMillis, const int soSendTimeoutMillis,
const bool dualStack, const bool tcpNoDelay, const bool keepAlive, const bool nonBlocking,
const bool autoConnect, const bool autoBind, const std::string_view localAddress, const Port localPort)
: SocketOptions(INVALID_SOCKET), _remoteAddr{}, _remoteAddrLen(0),
_internalBuffer(internalBufferSize.value_or(DefaultBufferSize))
{
_cliAddrInfo = internal::resolveAddress(host, port, dualStack ? AF_UNSPEC : AF_INET, SOCK_STREAM, IPPROTO_TCP);
// Try each candidate until socket creation succeeds
for (addrinfo* p = _cliAddrInfo.get(); p != nullptr; p = p->ai_next)
{
setSocketFd(::socket(p->ai_family, p->ai_socktype, p->ai_protocol));
if (getSocketFd() != INVALID_SOCKET)
{
_selectedAddrInfo = p;
break;
}
}
if (getSocketFd() == INVALID_SOCKET)
cleanupAndThrow(GetSocketError());
// --- Configure socket options before connect ---
setReuseAddress(reuseAddress);
setInternalBufferSize(_internalBuffer.size());
setReceiveBufferSize(recvBufferSize.value_or(DefaultBufferSize));
setSendBufferSize(sendBufferSize.value_or(DefaultBufferSize));
setTcpNoDelay(tcpNoDelay);
setKeepAlive(keepAlive);
setNonBlocking(nonBlocking);
if (soRecvTimeoutMillis >= 0)
setSoRecvTimeout(soRecvTimeoutMillis);
if (soSendTimeoutMillis >= 0)
setSoSendTimeout(soSendTimeoutMillis);
if (autoBind)
{
try
{
bind(localAddress, localPort);
}
catch (const SocketException&)
{
cleanupAndRethrow();
}
}
if (autoConnect)
{
// Blocking connect; user may later call non-blocking connect with timeout explicitly
connect();
}
}
void Socket::cleanup()
{
internal::tryCloseNoexcept(getSocketFd());
setSocketFd(INVALID_SOCKET);
_cliAddrInfo.reset();
_selectedAddrInfo = nullptr;
_isBound = false;
_isConnected = false;
resetShutdownFlags();
}
void Socket::cleanupAndThrow(const int errorCode)
{
cleanup();
throw SocketException(errorCode, SocketErrorMessage(errorCode));
}
void Socket::cleanupAndRethrow()
{
cleanup();
throw; // Preserve original exception
}
void Socket::bind(const std::string_view localHost, const Port port)
{
if (_isConnected)
{
throw SocketException("Socket::bind(): socket is already connected");
}
if (_isBound)
{
throw SocketException("Socket::bind(): socket is already bound");
}
const internal::AddrinfoPtr result =
internal::resolveAddress(localHost, port, AF_UNSPEC, SOCK_STREAM, IPPROTO_TCP, AI_PASSIVE);
for (const addrinfo* p = result.get(); p != nullptr; p = p->ai_next)
{
if (::bind(getSocketFd(), p->ai_addr,
#ifdef _WIN32
static_cast<int>(p->ai_addrlen)
#else
p->ai_addrlen
#endif
) == 0)
{
_isBound = true;
return; // success
}
}
const int error = GetSocketError();
throw SocketException(error, SocketErrorMessage(error));
}
void Socket::bind(const Port port)
{
bind("", port);
}
void Socket::bind()
{
bind("", 0);
}
void Socket::connect(const int timeoutMillis)
{
if (_isConnected)
{
throw SocketException("connect() called on an already-connected socket");
}
// Ensure that we have already selected an address during construction
if (_selectedAddrInfo == nullptr)
{
throw SocketException("connect() failed: no valid addrinfo found");
}
// Determine if we should use non-blocking connect logic
const bool useNonBlocking = (timeoutMillis >= 0);
// Automatically switch to non-blocking if needed, and restore original mode later
// NOLINTNEXTLINE - Temporarily switch to non-blocking mode (RAII-reverted)
std::optional<internal::ScopedBlockingMode> blockingGuard;
if (useNonBlocking)
{
blockingGuard.emplace(getSocketFd(), true); // Set non-blocking temporarily
}
// Attempt to initiate the connection
const auto res = ::connect(getSocketFd(), _selectedAddrInfo->ai_addr,
#ifdef _WIN32
static_cast<int>(_selectedAddrInfo->ai_addrlen)
#else
_selectedAddrInfo->ai_addrlen
#endif
);
if (res == SOCKET_ERROR)
{
const int error = GetSocketError();
// On most platforms, these errors indicate a non-blocking connection in progress
#ifdef _WIN32
const bool wouldBlock = (error == WSAEINPROGRESS || error == WSAEWOULDBLOCK);
#else
const bool wouldBlock = (error == EINPROGRESS || error == EWOULDBLOCK);
#endif
if (!useNonBlocking || !wouldBlock)
{
throw SocketException(error, SocketErrorMessage(error));
}
// Check FD_SETSIZE limit before using select()
if (getSocketFd() >= FD_SETSIZE)
{
throw SocketException("connect(): socket descriptor exceeds FD_SETSIZE (" + std::to_string(FD_SETSIZE) +
"), select() cannot be used");
}
// Wait until socket becomes writable (connection ready or failed)
timeval tv{};
tv.tv_sec = timeoutMillis / 1000;
tv.tv_usec = (timeoutMillis % 1000) * 1000;
fd_set writeFds;
FD_ZERO(&writeFds);
FD_SET(getSocketFd(), &writeFds);
#ifdef _WIN32
const int selectResult = ::select(0, nullptr, &writeFds, nullptr, &tv);
#else
int selectResult;
do
{
selectResult = ::select(getSocketFd() + 1, nullptr, &writeFds, nullptr, &tv);
} while (selectResult < 0 && errno == EINTR);
#endif
if (selectResult == 0)
throw SocketTimeoutException(JSOCKETPP_TIMEOUT_CODE,
"Connection timed out after " + std::to_string(timeoutMillis) + " ms");
if (selectResult < 0)
{
const int selectError = GetSocketError();
throw SocketException(selectError, SocketErrorMessage(selectError));
}
// Even if select() reports writable, we must check if the connection actually succeeded
int so_error = 0;
socklen_t len = sizeof(so_error);
// SO_ERROR is always retrieved as int (POSIX & Windows agree on semantics)
if (::getsockopt(getSocketFd(), SOL_SOCKET, SO_ERROR, reinterpret_cast<char*>(&so_error), &len) < 0 ||
so_error != 0)
{
throw SocketException(so_error, SocketErrorMessage(so_error));
}
}
_isConnected = true;
// Socket mode will be restored automatically via ScopedBlockingMode destructor
}
Socket::~Socket() noexcept
{
try
{
close();
}
catch (...)
{
// Suppress all exceptions to maintain noexcept guarantee.
// TODO: Consider adding an internal flag or user-configurable error handler
// to report destructor-time errors in future versions.
}
}
/**
* @brief Close the socket.
* @throws SocketException on error.
*/
void Socket::close()
{
internal::closeOrThrow(getSocketFd());
setSocketFd(INVALID_SOCKET);
_cliAddrInfo.reset();
_selectedAddrInfo = nullptr;
_isBound = false;
_isConnected = false;
resetShutdownFlags();
}
void Socket::shutdown(const ShutdownMode how) const
{
// Convert ShutdownMode to platform-specific shutdown constants
int shutdownType;
#ifdef _WIN32
switch (how)
{
case ShutdownMode::Read:
shutdownType = SD_RECEIVE;
break;
case ShutdownMode::Write:
shutdownType = SD_SEND;
break;
case ShutdownMode::Both:
[[fallthrough]]; // SD_BOTH is equivalent to SD_SEND | SD_RECEIVE
default:
shutdownType = SD_BOTH;
break;
}
#else
switch (how)
{
case ShutdownMode::Read:
shutdownType = SHUT_RD;
break;
case ShutdownMode::Write:
shutdownType = SHUT_WR;
break;
case ShutdownMode::Both:
[[fallthrough]]; // SHUT_RDWR is equivalent to SHUT_WR | SHUT_RD
default:
shutdownType = SHUT_RDWR;
break;
}
#endif
// Ensure the socket is valid before attempting to shutdown
if (getSocketFd() != INVALID_SOCKET)
{
if (::shutdown(getSocketFd(), shutdownType))
{
const int error = GetSocketError();
throw SocketException(error, SocketErrorMessage(error));
}
}
}
std::string Socket::getLocalIp(const bool convertIPv4Mapped) const
{
if (getSocketFd() == INVALID_SOCKET)
throw SocketException("getLocalIp() failed: socket is not open.");
sockaddr_storage addr{};
socklen_t addrLen = sizeof(addr);
if (::getsockname(getSocketFd(), reinterpret_cast<sockaddr*>(&addr), &addrLen) == SOCKET_ERROR)
{
const int error = GetSocketError();
throw SocketException(error, SocketErrorMessage(error));
}
return ipFromSockaddr(reinterpret_cast<const sockaddr*>(&addr), convertIPv4Mapped);
}
Port Socket::getLocalPort() const
{
if (getSocketFd() == INVALID_SOCKET)
throw SocketException("getLocalPort() failed: socket is not open.");
sockaddr_storage addr{};
socklen_t addrLen = sizeof(addr);
if (::getsockname(getSocketFd(), reinterpret_cast<sockaddr*>(&addr), &addrLen) == SOCKET_ERROR)
{
const int error = GetSocketError();
throw SocketException(error, SocketErrorMessage(error));
}
return portFromSockaddr(reinterpret_cast<const sockaddr*>(&addr));
}
std::string Socket::getLocalSocketAddress(const bool convertIPv4Mapped) const
{
return getLocalIp(convertIPv4Mapped) + ":" + std::to_string(getLocalPort());
}
std::string Socket::getRemoteIp(const bool convertIPv4Mapped) const
{
if (getSocketFd() == INVALID_SOCKET)
throw SocketException("getRemoteIp() failed: socket is not open.");
sockaddr_storage remoteAddr{};
socklen_t addrLen = sizeof(remoteAddr);
if (::getpeername(getSocketFd(), reinterpret_cast<sockaddr*>(&remoteAddr), &addrLen) == SOCKET_ERROR)
{
const int error = GetSocketError();
throw SocketException(error, SocketErrorMessage(error));
}
return ipFromSockaddr(reinterpret_cast<const sockaddr*>(&remoteAddr), convertIPv4Mapped);
}
Port Socket::getRemotePort() const
{
if (getSocketFd() == INVALID_SOCKET)
throw SocketException("getRemotePort() failed: socket is not open.");
sockaddr_storage remoteAddr{};
socklen_t addrLen = sizeof(remoteAddr);
if (::getpeername(getSocketFd(), reinterpret_cast<sockaddr*>(&remoteAddr), &addrLen) == SOCKET_ERROR)
{
const int error = GetSocketError();
throw SocketException(error, SocketErrorMessage(error));
}
return portFromSockaddr(reinterpret_cast<const sockaddr*>(&remoteAddr));
}
std::string Socket::getRemoteSocketAddress(const bool convertIPv4Mapped) const
{
return getRemoteIp(convertIPv4Mapped) + ":" + std::to_string(getRemotePort());
}
size_t Socket::write(const std::string_view message) const
{
int flags = 0;
#ifndef _WIN32
flags = MSG_NOSIGNAL; // Prevent SIGPIPE on write to a closed socket (POSIX)
#endif
const auto len = send(getSocketFd(), message.data(),
#ifdef _WIN32
static_cast<int>(message.size()), // Windows: cast to int
#else
static_cast<size_t>(message.size()), // Linux/Unix: use size_t directly
#endif
flags);
if (len == SOCKET_ERROR)
{
const int error = GetSocketError();
throw SocketException(error, SocketErrorMessage(error));
}
// send() may send fewer bytes than requested (partial write), especially on non-blocking sockets.
// It is the caller's responsibility to check the return value and handle partial sends if needed.
return static_cast<size_t>(len);
}
// Write all data, retrying as needed until all bytes are sent or an error occurs.
// Returns the total number of bytes sent (should be message.size() on success).
size_t Socket::writeAll(const std::string_view message) const
{
std::size_t totalSent = 0;
while (totalSent < message.size())
{
const auto sent = write(message.substr(totalSent));
if (sent == 0)
throw SocketException("Connection closed during writeAll()");
totalSent += static_cast<std::size_t>(sent);
}
return totalSent;
}
void Socket::setInternalBufferSize(const std::size_t newLen)
{
_internalBuffer.resize(newLen);
_internalBuffer.shrink_to_fit();
}
bool Socket::waitReady(const bool forWrite, const int timeoutMillis) const
{
if (getSocketFd() == INVALID_SOCKET)
throw SocketException("Invalid socket");
// Guard against file descriptors exceeding FD_SETSIZE, which causes UB in FD_SET()
if (getSocketFd() >= FD_SETSIZE)
{
throw SocketException("Socket descriptor exceeds FD_SETSIZE (" + std::to_string(FD_SETSIZE) +
"), cannot use select()");
}
fd_set fds;
FD_ZERO(&fds);
FD_SET(getSocketFd(), &fds);
// Default to zero-timeout for non-blocking poll
timeval tv{0, 0};
if (timeoutMillis >= 0)
{
tv.tv_sec = timeoutMillis / 1000;
tv.tv_usec = (timeoutMillis % 1000) * 1000;
}
int result;
#ifdef _WIN32
// On Windows, the first argument to select() is ignored but must be >= 0.
result = select(0, forWrite ? nullptr : &fds, forWrite ? &fds : nullptr, nullptr, &tv);
#else
// On POSIX, first argument must be the highest fd + 1
result =
select(static_cast<int>(getSocketFd()) + 1, forWrite ? nullptr : &fds, forWrite ? &fds : nullptr, nullptr, &tv);
#endif
if (result < 0)
{
const int error = GetSocketError();
throw SocketException(error, SocketErrorMessage(error));
}
return result > 0;
}
std::string Socket::readExact(const std::size_t n) const
{
if (n == 0)
return {};
std::string result;
result.resize(n); // pre-allocate for performance
std::size_t totalRead = 0;
while (totalRead < n)
{
const auto remaining = n - totalRead;
const auto len = recv(getSocketFd(), result.data() + totalRead,
#ifdef _WIN32
static_cast<int>(remaining),
#else
remaining,
#endif
0);
if (len == SOCKET_ERROR)
{
const int error = GetSocketError();
throw SocketException(error, SocketErrorMessage(error));
}
if (len == 0)
throw SocketException("Connection closed before reading all data.");
totalRead += static_cast<std::size_t>(len);
}
return result;
}
std::string Socket::readUntil(const char delimiter, const std::size_t maxLen, const bool includeDelimiter)
{
if (maxLen == 0)
{
throw SocketException("readUntil: maxLen must be greater than 0.");
}
std::string result;
result.reserve(std::min<std::size_t>(128, maxLen)); // Preallocate small buffer
std::size_t totalRead = 0;
while (totalRead < maxLen)
{
const std::size_t toRead = (std::min) (_internalBuffer.size(), maxLen - totalRead);
const auto len = recv(getSocketFd(), _internalBuffer.data(),
#ifdef _WIN32
static_cast<int>(toRead),
#else
toRead,
#endif
0);
if (len == SOCKET_ERROR)
{
const int error = GetSocketError();
throw SocketException(error, SocketErrorMessage(error));
}
if (len == 0)
throw SocketException("readUntil: connection closed before delimiter was found.");
for (std::size_t i = 0; i < static_cast<std::size_t>(len); ++i)
{
const char ch = _internalBuffer[i];
if (totalRead >= maxLen)
{
throw SocketException("readUntil: exceeded maximum read limit without finding delimiter.");
}
result.push_back(ch);
++totalRead;
if (ch == delimiter)
{
if (!includeDelimiter)
{
result.pop_back();
}
return result;
}
}
}
throw SocketException("readUntil: maximum length reached without finding delimiter.");
}
std::string Socket::readAtMost(std::size_t n) const
{
if (n == 0)
{
// Nothing to read, return empty string immediately
return {};
}
std::string result(n, '\0'); // Preallocate n bytes initialized to null
const auto len = recv(getSocketFd(), result.data(),
#ifdef _WIN32
static_cast<int>(n),
#else
n,
#endif
0);
if (len == SOCKET_ERROR)
{
const int error = GetSocketError();
throw SocketException(error, SocketErrorMessage(error));
}
if (len == 0)
{
throw SocketException("readAtMost: connection closed by remote host.");
}
result.resize(static_cast<std::size_t>(len)); // Trim to actual number of bytes read
return result;
}
std::size_t Socket::readIntoInternal(void* buffer, std::size_t len, const bool exact) const
{
if (buffer == nullptr || len == 0)
return 0;
const auto out = static_cast<char*>(buffer);
std::size_t totalRead = 0;
do
{
const auto bytesRead = recv(getSocketFd(), out + totalRead,
#ifdef _WIN32
static_cast<int>(len - totalRead),
#else
len - totalRead,
#endif
0);
if (bytesRead == SOCKET_ERROR)
{
const int error = GetSocketError();
throw SocketException(error, SocketErrorMessage(error));
}
if (bytesRead == 0)
{
if (exact)
throw SocketException("Connection closed before full read completed.");
break; // return what we got so far
}
totalRead += static_cast<std::size_t>(bytesRead);
} while (exact && totalRead < len);
return totalRead;
}
std::string Socket::readAtMostWithTimeout(std::size_t n, const int timeoutMillis) const
{
if (n == 0)
return {};
if (!waitReady(false /* forRead */, timeoutMillis))
throw SocketTimeoutException(JSOCKETPP_TIMEOUT_CODE,
"Read timed out after waiting " + std::to_string(timeoutMillis) + " ms");
std::string result;
result.resize(n); // max allocation
const auto len = recv(getSocketFd(), result.data(),
#ifdef _WIN32
static_cast<int>(n),
#else
n,
#endif
0);
if (len == SOCKET_ERROR)
{
const int error = GetSocketError();
throw SocketException(error, SocketErrorMessage(error));
}
if (len == 0)
throw SocketException("Connection closed before data could be read.");
result.resize(static_cast<std::size_t>(len)); // shrink to actual
return result;
}
std::string Socket::readAvailable() const
{
if (getSocketFd() == INVALID_SOCKET)
throw SocketException("readAvailable() called on invalid socket");
#ifdef _WIN32
u_long bytesAvailable = 0;
if (ioctlsocket(getSocketFd(), FIONREAD, &bytesAvailable) != 0)
{
const int error = GetSocketError();
throw SocketException(error, SocketErrorMessage(error));
}
#else
int bytesAvailable = 0;
if (ioctl(getSocketFd(), FIONREAD, &bytesAvailable) < 0)
{
const int error = GetSocketError();
throw SocketException(error, SocketErrorMessage(error));
}
#endif
if (bytesAvailable <= 0)
return {};
std::string result;
result.resize(static_cast<std::size_t>(bytesAvailable));
const auto len = recv(getSocketFd(), result.data(),
#ifdef _WIN32
static_cast<int>(bytesAvailable),
#else
static_cast<std::size_t>(bytesAvailable),
#endif
0);
if (len == SOCKET_ERROR)
{
const int error = GetSocketError();
throw SocketException(error, SocketErrorMessage(error));
}
if (len == 0)
throw SocketException("Connection closed while attempting to read available data.");
result.resize(static_cast<std::size_t>(len)); // shrink to actual read
return result;
}
std::size_t Socket::readIntoAvailable(void* buffer, const std::size_t bufferSize) const
{
if (getSocketFd() == INVALID_SOCKET)
throw SocketException("readIntoAvailable() called on invalid socket");
if (buffer == nullptr || bufferSize == 0)
return 0;
#ifdef _WIN32
u_long bytesAvailable = 0;
if (ioctlsocket(getSocketFd(), FIONREAD, &bytesAvailable) != 0)
{
const int error = GetSocketError();
throw SocketException(error, SocketErrorMessage(error));
}
#else
int bytesAvailable = 0;
if (ioctl(getSocketFd(), FIONREAD, &bytesAvailable) < 0)
{
const int error = GetSocketError();
throw SocketException(error, SocketErrorMessage(error));
}
#endif
if (bytesAvailable <= 0)
return 0;
const std::size_t toRead = std::min<std::size_t>(static_cast<std::size_t>(bytesAvailable), bufferSize);
const auto len = recv(getSocketFd(),
#ifdef _WIN32
static_cast<char*>(buffer), static_cast<int>(toRead),
#else
buffer, toRead,
#endif
0);
if (len == SOCKET_ERROR)
{
const int error = GetSocketError();
throw SocketException(error, SocketErrorMessage(error));
}
if (len == 0)
throw SocketException("Connection closed while attempting to read available data.");
return static_cast<std::size_t>(len);
}
std::string Socket::peek(std::size_t n) const
{
if (getSocketFd() == INVALID_SOCKET)
throw SocketException("peek() called on invalid socket");
if (n == 0)
return {};
std::string result;
result.resize(n);
const auto len = recv(getSocketFd(), result.data(),
#ifdef _WIN32
static_cast<int>(n),
#else
n,
#endif
MSG_PEEK);
if (len == SOCKET_ERROR)
{
const int error = GetSocketError();
throw SocketException(error, SocketErrorMessage(error));
}
if (len == 0)
throw SocketException("Connection closed during peek operation.");
result.resize(static_cast<std::size_t>(len)); // trim to actual
return result;
}
void Socket::discard(const std::size_t n, const std::size_t chunkSize /* = 1024 */) const
{
if (getSocketFd() == INVALID_SOCKET)
throw SocketException("discard(): attempted on invalid socket.");
if (n == 0)
return;
if (chunkSize == 0)
throw SocketException("discard(): chunkSize must be greater than zero.");
std::vector<char> tempBuffer(chunkSize); // Heap-allocated scratch buffer
std::size_t totalDiscarded = 0;
while (totalDiscarded < n)
{
const std::size_t toRead = (std::min) (chunkSize, n - totalDiscarded);
const auto len = recv(getSocketFd(), tempBuffer.data(),
#ifdef _WIN32
static_cast<int>(toRead),
#else
toRead,
#endif
0);
if (len == SOCKET_ERROR)
{
const int error = GetSocketError();
throw SocketException(error, SocketErrorMessage(error));
}
if (len == 0)
{
throw SocketException("discard(): connection closed before all bytes were discarded.");
}
totalDiscarded += static_cast<std::size_t>(len);
}
}
std::size_t Socket::writev(std::span<const std::string_view> buffers) const
{
if (getSocketFd() == INVALID_SOCKET)
throw SocketException("writev() called on invalid socket");
#ifdef _WIN32
// Convert to WSABUF
std::vector<WSABUF> wsabufs;
wsabufs.reserve(buffers.size());
for (const auto& buf : buffers)
{
WSABUF w;
w.buf = const_cast<char*>(buf.data()); // WSABUF is not const-correct
w.len = static_cast<ULONG>(buf.size());
wsabufs.push_back(w);
}
DWORD bytesSent = 0;
if (const int result =
WSASend(getSocketFd(), wsabufs.data(), static_cast<DWORD>(wsabufs.size()), &bytesSent, 0, nullptr, nullptr);
result == SOCKET_ERROR)
{
const int error = GetSocketError();
throw SocketException(error, SocketErrorMessage(error));
}
return static_cast<std::size_t>(bytesSent);
#else
// POSIX: use writev
std::vector<iovec> iovecs;
iovecs.reserve(buffers.size());
for (const auto& buf : buffers)
{
iovec io{};
io.iov_base = const_cast<char*>(buf.data()); // iovec is not const-correct either
io.iov_len = buf.size();
iovecs.push_back(io);
}
ssize_t bytesSent = ::writev(getSocketFd(), iovecs.data(), static_cast<int>(iovecs.size()));
if (bytesSent == -1)
{
const int error = GetSocketError();
throw SocketException(error, SocketErrorMessage(error));
}
return static_cast<std::size_t>(bytesSent);
#endif
}
std::size_t Socket::writevAll(std::span<const std::string_view> buffers) const
{
std::vector remainingBuffers(buffers.begin(), buffers.end());
std::size_t totalSent = 0;
while (!remainingBuffers.empty())
{
const std::size_t bytesSent = writev(remainingBuffers);
totalSent += bytesSent;
std::size_t advanced = 0;
std::size_t remaining = bytesSent;
// Count how many buffers were fully sent
for (const auto& buf : remainingBuffers)
{
if (remaining >= buf.size())
{
remaining -= buf.size();
++advanced;
}
else
{
break;
}
}
// Erase fully sent buffers
remainingBuffers.erase(remainingBuffers.begin(),
remainingBuffers.begin() +
static_cast<std::vector<std::string_view>::difference_type>(advanced));
// Adjust the partially sent first buffer
if (!remainingBuffers.empty() && remaining > 0)
{
remainingBuffers[0] = remainingBuffers[0].substr(remaining);
}
}
return totalSent;
}
std::size_t Socket::writeAtMostWithTimeout(std::string_view data, const int timeoutMillis) const
{
if (getSocketFd() == INVALID_SOCKET)
throw SocketException("writeAtMostWithTimeout() called on invalid socket");
if (data.empty())
return 0;
if (!waitReady(true /* forWrite */, timeoutMillis))
throw SocketTimeoutException(JSOCKETPP_TIMEOUT_CODE,
"Write timed out after " + std::to_string(timeoutMillis) + " ms");
const auto len = send(getSocketFd(),
#ifdef _WIN32
data.data(), static_cast<int>(data.size()),
#else
data.data(), data.size(),
#endif
0);
if (len == SOCKET_ERROR)
{
const int error = GetSocketError();
throw SocketException(error, SocketErrorMessage(error));
}
if (len == 0)
throw SocketException("Connection closed while writing.");
return static_cast<std::size_t>(len);
}
std::size_t Socket::writeFrom(const void* data, std::size_t len) const
{
if (getSocketFd() == INVALID_SOCKET)