internal ConsoleSession(WTS_SESSION_INFO_1 info) { SessionId = info.SessionId; UserName = info.pUserName ?? string.Empty; SessionName = info.pSessionName ?? string.Empty; State = info.State; DomainName = info.pDomainName ?? string.Empty; HostName = info.pHostName ?? string.Empty; FarmName = info.pFarmName ?? string.Empty; }
public static List <Dictionary <string, string> > GetRDPSessions() { List <Dictionary <string, string> > results = new List <Dictionary <string, string> >(); // adapted from http://www.pinvoke.net/default.aspx/wtsapi32.wtsenumeratesessions IntPtr server = IntPtr.Zero; List <String> ret = new List <string>(); server = OpenServer("localhost"); try { IntPtr ppSessionInfo = IntPtr.Zero; Int32 count = 0; Int32 level = 1; Int32 retval = WTSEnumerateSessionsEx(server, ref level, 0, ref ppSessionInfo, ref count); Int32 dataSize = Marshal.SizeOf(typeof(WTS_SESSION_INFO_1)); Int64 current = (Int64)ppSessionInfo; if (retval != 0) { for (int i = 0; i < count; i++) { Dictionary <string, string> rdp_session = new Dictionary <string, string>(); WTS_SESSION_INFO_1 si = (WTS_SESSION_INFO_1)Marshal.PtrToStructure((System.IntPtr)current, typeof(WTS_SESSION_INFO_1)); current += dataSize; if (si.pUserName == null || si.pUserName == "") { continue; } rdp_session["SessionID"] = String.Format("{0}", si.SessionID); rdp_session["pSessionName"] = String.Format("{0}", si.pSessionName); rdp_session["pUserName"] = String.Format("{0}", si.pUserName); rdp_session["pDomainName"] = String.Format("{0}", si.pDomainName); rdp_session["State"] = String.Format("{0}", si.State); rdp_session["SourceIP"] = ""; // Now use WTSQuerySessionInformation to get the remote IP (if any) for the connection IntPtr addressPtr = IntPtr.Zero; uint bytes = 0; WTSQuerySessionInformation(server, (uint)si.SessionID, WTS_INFO_CLASS.WTSClientAddress, out addressPtr, out bytes); WTS_CLIENT_ADDRESS address = (WTS_CLIENT_ADDRESS)Marshal.PtrToStructure((System.IntPtr)addressPtr, typeof(WTS_CLIENT_ADDRESS)); if (address.Address[2] != 0) { string sourceIP = String.Format("{0}.{1}.{2}.{3}", address.Address[2], address.Address[3], address.Address[4], address.Address[5]); rdp_session["SourceIP"] = String.Format("{0}", sourceIP); } results.Add(rdp_session); } WTSFreeMemory(ppSessionInfo); } } catch (Exception ex) { Beaprint.GrayPrint(String.Format(" [X] Exception: {0}", ex)); } finally { CloseServer(server); } return(results); }