You can get a connection state using the netstat command (a connection state is something like ESTABLISHED or TIME_WAIT and so on).
But can you get the connection state of a socket programmatically?
CodePudding user response:
You can't query a SOCKET itself for the kind of state you are wanting.
But, you can query the socket for its type (TCP vs UDP) and IP/Port pairs assigned to it (ie, via getsockopt() with SO_BSP_STATE, or via getsockopt(SO_TYPE) getsockname() getpeername()), and then you can enumerate Windows' TCP/UDP tables until you find an entry that matches those same details, then you will have the state from that entry.
Have a look at the following enumeration functions:
TCP:
GetTcpTable()/GetTcpTable2()(IPv4 only)GetTcp6Table()/GetTcp6Table2()(IPv6 only)GetExtendedTcpTable()(both IPv4 and IPv6)
UDP:
GetUdpTable()(IPv4 only)GetUdp6Table()(IPv6 only)GetExtendedUdpTable()(both IPv4 and IPv6)
CodePudding user response:
On Windows, you can use getsockopt() with the SO_BSP_STATE option to get at least some information about the state of a socket:
The
SO_BSP_STATEsocket option returns the local address, local port, remote address, remote port, socket type, and protocol used by a socket.To perform this operation, call the
getsockoptfunction with the following parameters.Socket option value The constant that represents this socket option is 0x1009.
Syntax C
int getsockopt( (SOCKET) s, // descriptor identifying a socket (int) SOL_SOCKET, // level (int) SO_BSP_STATE, // optname (char *) optval, // output buffer, (int) *optlen, // size of output buffer );Parameters
s [in]
A descriptor identifying the socket.
level [in]
The level at which the option is defined. Use SOL_SOCKET for this operation.
optname [in]
The socket option for which the value is to be retrieved. Use
SO_BSP_STATEfor this operation.optval [out]
A pointer to the buffer in which the value for the requested option is to be returned. This parameter should point to buffer equal to or larger than the size of a
CSADDR_INFOstructure.optlen [in, out]
A pointer to the size, in bytes, of the optval buffer. This size must be equal to or larger than the size of a
CSADDR_INFOstructure.Return value
If the operation completes successfully,
getsockoptreturns zero.If the operation fails, a value of
SOCKET_ERRORis returned and a specific error code can be retrieved by callingWSAGetLastError.
A CSADDR_INFO structure is defined as
typedef struct _CSADDR_INFO {
SOCKET_ADDRESS LocalAddr;
SOCKET_ADDRESS RemoteAddr;
INT iSocketType;
INT iProtocol;
} CSADDR_INFO, *PCSADDR_INFO, *LPCSADDR_INFO;
