4

我需要从用户的终端服务器会话中获取底层客户端 PC 名称。

我知道它存在,HKEY_CURRENT_USER\Volatile Environment\CLIENTNAME但是否有另一种(最好是原生 .net)方法来获取它?

4

2 回答 2

14

我没有看到用于此的托管 API。我可以看到获取此信息的唯一基于 API 的方法是通过 WMI 或 Windows 中的本机终端服务 API。

下面是一个使用WTSQuerySessionInformationAPI 返回客户端名称的示例:

namespace com.stackoverflow
{
    using System;
    using System.Runtime.InteropServices;

    public class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(GetTerminalServicesClientName());
        }

        /// <summary>
        /// Gets the name of the client system.
        /// </summary>
        internal static string GetTerminalServicesClientName()
        {
            IntPtr buffer = IntPtr.Zero;

            string clientName = null;
            int bytesReturned;

            bool success = NativeMethods.WTSQuerySessionInformation(
                NativeMethods.WTS_CURRENT_SERVER_HANDLE,
                NativeMethods.WTS_CURRENT_SESSION,
                NativeMethods.WTS_INFO_CLASS.WTSClientName,
                out buffer,
                out bytesReturned);

            if (success)
            {
                clientName = Marshal.PtrToStringUni(
                    buffer,
                    bytesReturned / 2 /* Because the DllImport uses CharSet.Unicode */
                    );
                NativeMethods.WTSFreeMemory(buffer);
            }

            return clientName;
        }
    }

    public static class NativeMethods
    {
        public static readonly IntPtr WTS_CURRENT_SERVER_HANDLE = IntPtr.Zero;
        public const int WTS_CURRENT_SESSION = -1;

        public enum WTS_INFO_CLASS
        {
            WTSClientName = 10
        }

        [DllImport("Wtsapi32.dll", CharSet = CharSet.Unicode)]
        public static extern bool WTSQuerySessionInformation(
            IntPtr hServer,
            Int32 sessionId,
            WTS_INFO_CLASS wtsInfoClass,
            out IntPtr ppBuffer,
            out Int32 pBytesReturned);

        /// <summary>
        /// The WTSFreeMemory function frees memory allocated by a Terminal
        /// Services function.
        /// </summary>
        /// <param name="memory">Pointer to the memory to free.</param>
        [DllImport("wtsapi32.dll", ExactSpelling = true, SetLastError = false)]
        public static extern void WTSFreeMemory(IntPtr memory);
    }
}
于 2011-03-16T04:54:03.333 回答
2

为了完成这些答案,Citrix Developer Network网站上托管了一个 C# 项目,该项目提供代码来列出 RDP 服务器上的会话及其 IP 地址:

如何使用终端服务 API 获取客户端 IP 地址和客户端主机名

于 2011-10-18T08:05:18.207 回答