Home > database >  Can you get the connection state of a socket programmatically?
Can you get the connection state of a socket programmatically?

Time:08-12

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:

UDP:

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_STATE socket 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 getsockopt function 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_STATE for 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_INFO structure.

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_INFO structure.

Return value

If the operation completes successfully, getsockopt returns zero.

If the operation fails, a value of SOCKET_ERROR is returned and a specific error code can be retrieved by calling WSAGetLastError.

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;
  • Related