Skip to content

Commit 5bac7e4

Browse files
committed
net: extend Sock with a method to check whether connected
This will be convenient in the I2P SAM implementation.
1 parent 42c779f commit 5bac7e4

File tree

2 files changed

+32
-0
lines changed

2 files changed

+32
-0
lines changed

src/util/sock.cpp

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -250,6 +250,31 @@ std::string Sock::RecvUntilTerminator(uint8_t terminator,
250250
}
251251
}
252252

253+
bool Sock::IsConnected(std::string& errmsg) const
254+
{
255+
if (m_socket == INVALID_SOCKET) {
256+
errmsg = "not connected";
257+
return false;
258+
}
259+
260+
char c;
261+
switch (Recv(&c, sizeof(c), MSG_PEEK)) {
262+
case -1: {
263+
const int err = WSAGetLastError();
264+
if (IOErrorIsPermanent(err)) {
265+
errmsg = NetworkErrorString(err);
266+
return false;
267+
}
268+
return true;
269+
}
270+
case 0:
271+
errmsg = "closed";
272+
return false;
273+
default:
274+
return true;
275+
}
276+
}
277+
253278
#ifdef WIN32
254279
std::string NetworkErrorString(int err)
255280
{

src/util/sock.h

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -143,6 +143,13 @@ class Sock
143143
std::chrono::milliseconds timeout,
144144
CThreadInterrupt& interrupt) const;
145145

146+
/**
147+
* Check if still connected.
148+
* @param[out] err The error string, if the socket has been disconnected.
149+
* @return true if connected
150+
*/
151+
virtual bool IsConnected(std::string& errmsg) const;
152+
146153
private:
147154
/**
148155
* Contained socket. `INVALID_SOCKET` designates the object is empty.

0 commit comments

Comments
 (0)