4.4 Legacy Example
The following example shows how to enumerate sessions that use the legacy RPC methods.
Get the binding.
Result = TermSrvBindSecure( pszUuid, pszRemoteProtocolSequence, pServerName, pszRemoteEndPoint, pszOptions, &RpcTSHandle ); // // Get a context handle from the server so it can // manage the connections state // RpcTryExcept { rc = RpcWinStationOpenServer( RpcTSHandle, &Result, &ContextHandle ); } RpcExcept(I_RpcExceptionFilter(RpcExceptionCode())) { Result = RpcExceptionCode(); rc = FALSE; wprintf(L"ERR: RPC Exception %d\n",Result ); } RpcEndExceptEnumerate the sessions.
RpcTryExcept { rc = RpcWinStationEnumerate( hServer, &Result, &LogonIdCount, (PCHAR)pLogonId, &Length, &Index ); Result = RtlNtStatusToDosError( Result ); if ( Result == ERROR_NO_MORE_ITEMS) { Result = ERROR_SUCCESS; break; } if(rc == TRUE) { wprintf(L"SessionID State Name\n"); for(ULONG i=0;i<LogonIdCount;i++) { wprintf(L"%-10d %-20s %-40s\n", pLogonId[i].SessionId, WinstationStateClassNames[pLogonId[i].State], pLogonId[i].WinStationName); } } } RpcExcept(I_RpcExceptionFilter(RpcExceptionCode())) { Result = RpcExceptionCode(); wprintf(L"ERR: RPC Exception %d\n",Result ); } RpcEndExceptClose the binding handles.
RpcTryExcept { bSuccess = RpcWinStationCloseServerEx( pHandle, pdwResult ); if( !bSuccess ) *pdwResult = RtlNtStatusToDosError( *pdwResult ); } RpcExcept(I_RpcExceptionFilter(RpcExceptionCode())) { *pdwResult = RpcExceptionCode(); bSuccess = FALSE; } RpcEndExcept
The following diagram illustrates the message sequence for enumerating the sessions.

Figure 2: Legacy session enumeration sequence
The sequence of messages for enumerating sessions on the server is as follows:
After an RPC binding has been established to the server, the client requests a handle to the server to be opened by calling the RpcWinStationOpenServer method.
The server in response will open up a handle and return to the client.
The client then calls the RpcWinStationEnumerate method by passing this handle along with an uninitialized buffer to get the list of sessions.
The server on receiving the request will allocate memory for the buffer and fill it with an array of LOGONID structures containing session information, one for each session on the server. It will also return the number of sessions on the server.
The client, on receiving the data, calls the RpcWinStationCloseServerEx method to inform the server to close the server handle.
The server on receiving the RpcWinStationCloseServerEx call will close the server handle.
The client frees the array of SESSIONENUM structures it received before exiting.