jsocketpp 1.0
A cross-platform C++20 socket library.
Loading...
Searching...
No Matches
common.hpp
Go to the documentation of this file.
1
5
6#pragma once
7
8#include "SocketException.hpp"
9
10#ifdef __GNUC__
11#define QUOTE(s) #s
12#define DIAGNOSTIC_PUSH() _Pragma("GCC diagnostic push")
13#define DIAGNOSTIC_IGNORE(warning) _Pragma(QUOTE(GCC diagnostic ignored warning))
14#define DIAGNOSTIC_POP() _Pragma("GCC diagnostic pop")
15#else
16#define DIAGNOSTIC_PUSH()
17#define DIAGNOSTIC_IGNORE(warning)
18#define DIAGNOSTIC_POP()
19#endif
20
21#include <cstring> // Use std::memset()
22#include <exception>
23#include <iostream>
24#include <memory>
25#include <string>
26#include <string_view>
27#include <utility>
28#include <vector>
29
30#ifdef _WIN32
31
32// Do not reorder includes here, because Windows headers have specific order requirements.
33// clang-format off
34#include <winsock2.h> // Must come first: socket, bind, listen, accept, etc.
35#include <ws2tcpip.h> // TCP/IP functions: getaddrinfo, getnameinfo, inet_ntop, inet_pton
36#include <windows.h> // General Windows headers (e.g., FormatMessageA)
37#include <iphlpapi.h> // GetAdaptersInfo, network adapter info
38// clang-format on
39
40// https://msdn.microsoft.com/en-us/library/6sehtctf.aspx
41#if !defined(WINVER) || (WINVER < _WIN32_WINNT_WINXP)
42#error WINVER must be defined to something equal or above to 0x0501 // Win XP
43#endif // WINVER
44#if !defined(_WIN32_WINNT) || (_WIN32_WINNT < _WIN32_WINNT_WINXP)
45#error _WIN32_WINNT must be defined to something equal or above to 0x0501 // Win XP
46#endif // _WIN32_WINNT
47
48/* If compiled with Visual C++
49 * https://msdn.microsoft.com/en-us/library/windows/desktop/ms737629%28v=vs.85%29.aspx
50 * http://stackoverflow.com/questions/3484434/what-does-pragma-comment-mean
51 * http://stackoverflow.com/questions/70013/how-to-detect-if-im-compiling-code-with-visual-studio-2008
52 */
53#ifdef _MSC_VER
54#pragma comment(lib, "Ws2_32.lib") // Winsock library
55#pragma comment(lib, "iphlpapi.lib") // GetAdaptersInfo
56#endif
57
58#else
59
60// Assuming Linux
61#include <arpa/inet.h> //for inet_ntoa
62#include <cerrno> //errno
63#include <cstring> //strerror
64#include <fcntl.h> //fcntl
65#include <ifaddrs.h> //getifaddrs
66#include <net/if.h> //if_nametoindex
67#include <netdb.h> //for struct addrinfo
68#include <netinet/in.h> //for sockaddr_in and sockaddr_in6
69#include <netinet/tcp.h> //TCP_NODELAY, TCP_MAXSEG
70#include <poll.h> //poll
71#include <sys/ioctl.h> //ioctl
72#include <sys/select.h> //select
73#include <sys/socket.h> //socket
74#include <sys/time.h> //timeval
75#include <sys/types.h> //socket
76#include <sys/uio.h> //writev,readv,iovec
77#include <sys/un.h> //for Unix domain sockets
78#include <unistd.h> //close
79
80#endif
81
99
120
131
137
143
149
155
187namespace jsocketpp
188{
189#ifdef _WIN32
190
191inline int InitSockets()
192{
193 WSADATA WSAData;
194 return WSAStartup(MAKEWORD(2, 2), &WSAData);
195}
196
197inline int CleanupSockets()
198{
199 return WSACleanup();
200}
201
202inline int GetSocketError()
203{
204 return WSAGetLastError();
205}
206
207// NOLINTNEXTLINE(misc-const-correctness) - changes socket state
208inline int CloseSocket(SOCKET fd)
209{
210 return closesocket(fd);
211}
212
213const char* inet_ntop_aux(int af, const void* src, char* dst, socklen_t size);
214
215#define JSOCKETPP_TIMEOUT_CODE WSAETIMEDOUT
216
217#else
218
219typedef int SOCKET;
220constexpr SOCKET INVALID_SOCKET = -1;
221constexpr SOCKET SOCKET_ERROR = -1;
222typedef sockaddr_un SOCKADDR_UN;
223
224#define JSOCKETPP_TIMEOUT_CODE ETIMEDOUT
225
226constexpr int InitSockets()
227{
228 return 0;
229}
230constexpr int CleanupSockets()
231{
232 return 0;
233}
234inline int GetSocketError()
235{
236 return errno;
237}
238inline int CloseSocket(const SOCKET fd)
239{
240 return close(fd);
241}
242
243inline int ioctlsocket(const SOCKET fd, const long cmd, u_long* argp)
244{
245 return ioctl(fd, static_cast<unsigned long>(cmd), argp);
246}
247
248#endif
249
255std::vector<std::string> getHostAddr();
256
271std::string SocketErrorMessage(int error, [[maybe_unused]] bool gaiStrerror = false);
272
284std::string SocketErrorMessageWrap(int error, [[maybe_unused]] bool gaiStrerror = false);
285
291enum class ShutdownMode
292{
296};
297
315using Port = std::uint16_t;
316
352inline constexpr std::size_t DefaultBufferSize = 4096;
353
370inline bool isIPv4MappedIPv6(const sockaddr_in6* addr6)
371{
372 return IN6_IS_ADDR_V4MAPPED(&addr6->sin6_addr);
373}
374
389inline sockaddr_in convertIPv4MappedIPv6ToIPv4(const sockaddr_in6& addr6)
390{
391 sockaddr_in addr4{};
392 addr4.sin_family = AF_INET;
393 addr4.sin_port = addr6.sin6_port;
394 std::memcpy(&addr4.sin_addr.s_addr, addr6.sin6_addr.s6_addr + 12, sizeof(addr4.sin_addr.s_addr));
395 return addr4;
396}
397
398} // namespace jsocketpp
399
438namespace jsocketpp::net
439{
440
444inline uint16_t toNetwork(const uint16_t val)
445{
446 return htons(val);
447}
448
452inline uint32_t toNetwork(const uint32_t val)
453{
454 return htonl(val);
455}
456
460inline uint16_t fromNetwork(const uint16_t val)
461{
462 return ntohs(val);
463}
464
468inline uint32_t fromNetwork(const uint32_t val)
469{
470 return ntohl(val);
471}
472
473} // namespace jsocketpp::net
Exception class for socket-related errors in jsocketpp.
std::uint16_t Port
Type alias representing a TCP or UDP port number (1–65535).
Definition common.hpp:315
sockaddr_in convertIPv4MappedIPv6ToIPv4(const sockaddr_in6 &addr6)
Converts an IPv4-mapped IPv6 address to a pure IPv4 sockaddr_in.
Definition common.hpp:389
bool isIPv4MappedIPv6(const sockaddr_in6 *addr6)
Checks if a given sockaddr_in6 represents an IPv4-mapped IPv6 address.
Definition common.hpp:370
constexpr std::size_t DefaultBufferSize
Default internal buffer size (in bytes) for TCP socket read operations.
Definition common.hpp:352
Endianness utilities for network byte order conversion.
uint16_t toNetwork(const uint16_t val)
Converts a 16-bit unsigned integer from host to network byte order.
Definition common.hpp:444
uint16_t fromNetwork(const uint16_t val)
Converts a 16-bit unsigned integer from network to host byte order.
Definition common.hpp:460
A C++ socket library providing Java-style networking interfaces.
Definition BufferView.hpp:13
int CleanupSockets()
Definition common.hpp:197
std::vector< std::string > getHostAddr()
Get all local network interface addresses as strings.
Definition common.cpp:120
ShutdownMode
Enum for socket shutdown modes.
Definition common.hpp:292
@ Write
Shutdown write operations (SHUT_WR or SD_SEND)
Definition common.hpp:294
@ Both
Shutdown both read and write operations (SHUT_RDWR or SD_BOTH)
Definition common.hpp:295
@ Read
Shutdown read operations (SHUT_RD or SD_RECEIVE)
Definition common.hpp:293
int CloseSocket(SOCKET fd)
Definition common.hpp:208
std::string SocketErrorMessage(int error, bool gaiStrerror=false)
Returns a human-readable error message for a socket error code.
Definition common.cpp:5
std::string SocketErrorMessageWrap(int error, bool gaiStrerror=false)
Returns a human-readable error message for a socket error code, with exception safety.
Definition common.cpp:50
constexpr SOCKET INVALID_SOCKET
Definition common.hpp:220
const char * inet_ntop_aux(int af, const void *src, char *dst, socklen_t size)
Definition common.cpp:76
int ioctlsocket(const SOCKET fd, const long cmd, u_long *argp)
Definition common.hpp:243
sockaddr_un SOCKADDR_UN
Definition common.hpp:222
int GetSocketError()
Definition common.hpp:202
int SOCKET
Definition common.hpp:219
constexpr SOCKET SOCKET_ERROR
Definition common.hpp:221
int InitSockets()
Definition common.hpp:191