34

Here's the scenario:

You have a Windows server that users remotely connect to via RDP. You want your program (which runs as a service) to know who is currently connected. This may or may not include an interactive console session.

Please note that this is the not the same as just retrieving the current interactive user.

I'm guessing that there is some sort of API access to Terminal Services to get this info?

John Saunders
  • 160,644
  • 26
  • 247
  • 397
James
  • 2,404
  • 2
  • 28
  • 33

4 Answers4

38

Here's my take on the issue:

using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;

namespace EnumerateRDUsers
{
  class Program
  {
    [DllImport("wtsapi32.dll")]
    static extern IntPtr WTSOpenServer([MarshalAs(UnmanagedType.LPStr)] string pServerName);

    [DllImport("wtsapi32.dll")]
    static extern void WTSCloseServer(IntPtr hServer);

    [DllImport("wtsapi32.dll")]
    static extern Int32 WTSEnumerateSessions(
        IntPtr hServer,
        [MarshalAs(UnmanagedType.U4)] Int32 Reserved,
        [MarshalAs(UnmanagedType.U4)] Int32 Version,
        ref IntPtr ppSessionInfo,
        [MarshalAs(UnmanagedType.U4)] ref Int32 pCount);

    [DllImport("wtsapi32.dll")]
    static extern void WTSFreeMemory(IntPtr pMemory);

    [DllImport("wtsapi32.dll")]
    static extern bool WTSQuerySessionInformation(
        IntPtr hServer, int sessionId, WTS_INFO_CLASS wtsInfoClass, out IntPtr ppBuffer, out uint pBytesReturned);

    [StructLayout(LayoutKind.Sequential)]
    private struct WTS_SESSION_INFO
    {
      public Int32 SessionID;

      [MarshalAs(UnmanagedType.LPStr)]
      public string pWinStationName;

      public WTS_CONNECTSTATE_CLASS State;
    }

    public enum WTS_INFO_CLASS
    {
      WTSInitialProgram,
      WTSApplicationName,
      WTSWorkingDirectory,
      WTSOEMId,
      WTSSessionId,
      WTSUserName,
      WTSWinStationName,
      WTSDomainName,
      WTSConnectState,
      WTSClientBuildNumber,
      WTSClientName,
      WTSClientDirectory,
      WTSClientProductId,
      WTSClientHardwareId,
      WTSClientAddress,
      WTSClientDisplay,
      WTSClientProtocolType
    }

    public enum WTS_CONNECTSTATE_CLASS
    {
      WTSActive,
      WTSConnected,
      WTSConnectQuery,
      WTSShadow,
      WTSDisconnected,
      WTSIdle,
      WTSListen,
      WTSReset,
      WTSDown,
      WTSInit
    }

    static void Main(string[] args)
    {
      ListUsers(Environment.MachineName);
    }

    public static void ListUsers(string serverName)
    {
      IntPtr serverHandle = IntPtr.Zero;
      List<string> resultList = new List<string>();
      serverHandle = WTSOpenServer(serverName);

      try
      {
        IntPtr sessionInfoPtr = IntPtr.Zero;
        IntPtr userPtr = IntPtr.Zero;
        IntPtr domainPtr = IntPtr.Zero;
        Int32 sessionCount = 0;
        Int32 retVal = WTSEnumerateSessions(serverHandle, 0, 1, ref sessionInfoPtr, ref sessionCount);
        Int32 dataSize = Marshal.SizeOf(typeof(WTS_SESSION_INFO));
        IntPtr currentSession = sessionInfoPtr;
        uint bytes = 0;

        if (retVal != 0)
        {
          for (int i = 0; i < sessionCount; i++)
          {
            WTS_SESSION_INFO si = (WTS_SESSION_INFO)Marshal.PtrToStructure((System.IntPtr)currentSession, typeof(WTS_SESSION_INFO));
            currentSession += dataSize;

            WTSQuerySessionInformation(serverHandle, si.SessionID, WTS_INFO_CLASS.WTSUserName, out userPtr, out bytes);
            WTSQuerySessionInformation(serverHandle, si.SessionID, WTS_INFO_CLASS.WTSDomainName, out domainPtr, out bytes);

            Console.WriteLine("Domain and User: " + Marshal.PtrToStringAnsi(domainPtr) + "\\" + Marshal.PtrToStringAnsi(userPtr));

            WTSFreeMemory(userPtr); 
            WTSFreeMemory(domainPtr);
          }

          WTSFreeMemory(sessionInfoPtr);
        }
      }
      finally
      {
        WTSCloseServer(serverHandle);
      }

    }

  }
}
Herohtar
  • 5,347
  • 4
  • 31
  • 41
Magnus Johansson
  • 28,010
  • 19
  • 106
  • 164
  • 1
    Hi Magnus,I tried your code, but it just returned the logged in user to the current client system in my local LAN.Is there any way to get all logged in users with systems client name in a local LAN with the above code? – M_Mogharrabi Jan 22 '13 at 06:31
  • @M_Mogharrabi , sorry your question doesn't really make sense to me. This code is meant to be run on a server, I don't know what you mean by "current client system" Can you please re-phrase? – Magnus Johansson Jan 22 '13 at 10:03
  • @Magnus,Thanks for your reply,I want to get list of users who are logged in right now in a local network and i thought your code can do this(I did not know it should run on a server).So i tried on a client system but it just returned the user who had log in on that client system. – M_Mogharrabi Jan 26 '13 at 07:07
  • This code snippet is meant for returning logged in RD users on a specific server. – Magnus Johansson Jan 26 '13 at 10:59
  • should the server name be `\\servername` or `servername` because it can't connect for some reason – Si8 Apr 04 '17 at 15:29
22

Another option, if you don't want to deal with the P/Invokes yourself, would be to use the Cassia library:

using System;
using System.Security.Principal;
using Cassia;

namespace CassiaSample
{
    public static class Program
    {
        public static void Main(string[] args)
        {
            ITerminalServicesManager manager = new TerminalServicesManager();
            using (ITerminalServer server = manager.GetRemoteServer("your-server-name"))
            {
                server.Open();
                foreach (ITerminalServicesSession session in server.GetSessions())
                {
                    NTAccount account = session.UserAccount;
                    if (account != null)
                    {
                        Console.WriteLine(account);
                    }
                }
            }
        }
    }
}
marsh-wiggle
  • 2,508
  • 3
  • 35
  • 52
Dan Ports
  • 1,421
  • 9
  • 7
  • Cassia is great except you can't get the Source Network Address only the Client IP address which will be their internal network address if they are behind a router. – DaddioNTS Aug 11 '17 at 12:58
7

Ok, one solution to my own question.

You can use WMI to retreive a list of running processes. You can also look at the owners of these processes. If you look at the owners of "explorer.exe" (and remove the duplicates) you should end up with a list of logged in users.

James
  • 2,404
  • 2
  • 28
  • 33
  • An example of James' suggestion can be seen here: https://github.com/R-Smith/Splice-Admin/blob/master/Splice%20Admin/Classes/RemoteLogonSession.cs What's interesting is R-Smith took it a step further and checks if it's a server, use Remote Desktop Services API to retrieve session info. – Alberto Guerrero May 17 '20 at 18:39
  • 1
    The explorer solution is smart :) – dognose Sep 25 '21 at 19:12
1
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;

namespace TerminalServices
{
    class TSManager
    {
    [DllImport("wtsapi32.dll")]
    static extern IntPtr WTSOpenServer([MarshalAs(UnmanagedType.LPStr)] String pServerName);

    [DllImport("wtsapi32.dll")]
    static extern void WTSCloseServer(IntPtr hServer);

    [DllImport("wtsapi32.dll")]
    static extern Int32 WTSEnumerateSessions(
        IntPtr hServer, 
        [MarshalAs(UnmanagedType.U4)] Int32 Reserved,
        [MarshalAs(UnmanagedType.U4)] Int32 Version, 
        ref IntPtr ppSessionInfo,
        [MarshalAs(UnmanagedType.U4)] ref Int32 pCount);

    [DllImport("wtsapi32.dll")]
    static extern void WTSFreeMemory(IntPtr pMemory);

    [StructLayout(LayoutKind.Sequential)]
    private struct WTS_SESSION_INFO
    {
        public Int32 SessionID;

        [MarshalAs(UnmanagedType.LPStr)]
        public String pWinStationName;

        public WTS_CONNECTSTATE_CLASS State;
    }

    public enum WTS_CONNECTSTATE_CLASS
    {
        WTSActive,
        WTSConnected,
        WTSConnectQuery,
        WTSShadow,
        WTSDisconnected,
        WTSIdle,
        WTSListen,
        WTSReset,
        WTSDown,
        WTSInit
    } 

    public static IntPtr OpenServer(String Name)
    {
        IntPtr server = WTSOpenServer(Name);
        return server;
    }
    public static void CloseServer(IntPtr ServerHandle)
    {
        WTSCloseServer(ServerHandle);
    }
    public static List<String> ListSessions(String ServerName)
    {
        IntPtr server = IntPtr.Zero;
        List<String> ret = new List<string>();
        server = OpenServer(ServerName);

        try
        {
        IntPtr ppSessionInfo = IntPtr.Zero;

        Int32 count = 0;
        Int32 retval = WTSEnumerateSessions(server, 0, 1, ref ppSessionInfo, ref count);
        Int32 dataSize = Marshal.SizeOf(typeof(WTS_SESSION_INFO));

        Int32 current = (int)ppSessionInfo;

        if (retval != 0)
        {
            for (int i = 0; i < count; i++)
            {
            WTS_SESSION_INFO si = (WTS_SESSION_INFO)Marshal.PtrToStructure((System.IntPtr)current, typeof(WTS_SESSION_INFO));
            current += dataSize;

            ret.Add(si.SessionID + " " + si.State + " " + si.pWinStationName);
            }

            WTSFreeMemory(ppSessionInfo);
        }
        }
        finally
        {
        CloseServer(server);
        }

        return ret;
    }
    }
}
Nescio
  • 27,645
  • 10
  • 53
  • 72