diff --git a/lib/net.cpp b/lib/net.cpp index beacfcb7b..3f72dec7f 100644 --- a/lib/net.cpp +++ b/lib/net.cpp @@ -15,6 +15,26 @@ // https://wiki.openssl.org/index.php/SSL/TLS_Client +static std::string socket_error(int err) +{ + static char msgbuf[256] = { '\0' }; +#ifdef _WIN32 + FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, + NULL, + err, + MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), + msgbuf, + sizeof(msgbuf), + NULL); +#else + snprintf(msgbuf, sizeof(msgbuf), "%s", strerror(err)); +#endif + if (msgbuf[0] == '\0') { + snprintf(msgbuf, sizeof(msgbuf), "(No Error Text) - %d", err); + } + return std::string(msgbuf); +} + class SocketObject: public Object { public: SocketObject() {} @@ -133,9 +153,8 @@ class RawSocketObject: public SocketObject { std::vector buffer(n); int r = ::recv(handle, reinterpret_cast(const_cast(buffer.data())), n, 0); if (r < 0) { - int err = errno; - perror("recv"); - return Cell(std::vector {Cell(number_from_uint32(CHOICE_RecvResult_error)), Cell(utf8string(strerror(err)))}); + int err = socketerror; + return Cell(std::vector {Cell(number_from_uint32(CHOICE_RecvResult_error)), Cell(utf8string(socket_error(err)))}); } if (r == 0) { return Cell(std::vector {Cell(number_from_uint32(CHOICE_RecvResult_eof))}); @@ -150,8 +169,7 @@ class RawSocketObject: public SocketObject { socklen_t sin_len = sizeof(sin); int r = ::recvfrom(handle, reinterpret_cast(const_cast(buffer.data())), n, 0, reinterpret_cast(&sin), &sin_len); if (r < 0) { - int err = errno; - perror("recvfrom"); + int err = socketerror; return Cell(std::vector {Cell(number_from_uint32(CHOICE_RecvFromResult_error)), Cell(utf8string(strerror(err)))}); } if (r == 0) { diff --git a/src/socketx.h b/src/socketx.h index eece91497..f3ae556c2 100644 --- a/src/socketx.h +++ b/src/socketx.h @@ -3,6 +3,7 @@ #include typedef int socklen_t; #pragma warning(disable: 4127) // incompatible with FD_SET() +#define socketerror WSAGetLastError() #else @@ -15,5 +16,6 @@ typedef int socklen_t; typedef int SOCKET; const int INVALID_SOCKET = -1; inline void closesocket(int x) { close(x); } +#define socketerror errno #endif