【问题标题】:Finding IP address of physical machine when in a remote session在远程会话中查找物理机的 IP 地址
【发布时间】:2020-05-14 00:58:24
【问题描述】:

我查看了 stackoverflow,但它所描述的只是在远程工作时如何获取远程 IP 地址。这可以通过以下方式完成:

var ipHostEntry = Dns.GetHostEntry(string.Empty);
var ipAddressList = ipHostEntry.AddressList;
var ipv4Addresses = Array.FindAll(ipAddressList, a => a.AddressFamily == AddressFamily.InterNetwork);
result = ipv4Addresses[0].ToString();

result 是远程 IP 地址(或本地 IP 地址,具体取决于您是否在远程工作)。

但是,我想要以下内容:

  • 我正在远程工作(使用 RDP)
  • 我需要物理机的 IP(运行 RDP 的计算机连接到另一台机器),而不是远程机器

有什么方法可以使用 C# 来完成这个任务吗?

【问题讨论】:

  • “远程工作”是什么意思?你是通过 RDP 连接的吗? “物理机的 IP”是指 RDP 客户端的 IP
  • 如果它是一个 RDP,那么 PInvoke WTSQuerySessionInformation 应该做的事情...... 编辑: 也可以快速谷歌搜索:C# getting RDP client IP 返回大量信息
  • 我已经更新了我的问题。这确实是RDP。我会调查的

标签: c# networking network-programming ip


【解决方案1】:

我阅读了很多行代码并浏览了很多文档页面,但这帮助我解决了这个问题:https://www.codeproject.com/Articles/111430/Grabbing-Information-of-a-Terminal-Services-Sessio

以上内容可帮助您获取所有会话及其对应 IP 地址的列表。但是,如果您与一台远程服务器有许多 RDP 连接,那么您将想要获取特定客户端的 IP 地址,我这样解决了:

[DllImport("Kernel32.dll")]
static extern int GetCurrentProcessId();

[DllImport("Kernel32.dll")]
static extern int ProcessIdToSessionId(int dwProcessid, ref int pSessionId);

[StructLayout(LayoutKind.Sequential)]
private struct WTS_CLIENT_ADDRESS
{
    public int iAddressFamily;
    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 20)]
    public byte[] bAddress;
}

private static string GetIpAddressFromSession(int sessionId, IntPtr server)
{
    var ipAddress = string.Empty;
    if (WTSQuerySessionInformation(server, sessionId, WTS_INFO_CLASS.WTSClientAddress, out IntPtr ipAddressPointer, out uint returnedBytes) == true)
    {
        var clientAddress = new WTS_CLIENT_ADDRESS();
        clientAddress = (WTS_CLIENT_ADDRESS)Marshal.PtrToStructure(ipAddressPointer, clientAddress.GetType());

        ipAddress = string.Format("{0}.{1}.{2}.{3}", clientAddress.bAddress[2], clientAddress.bAddress[3], clientAddress.bAddress[4], clientAddress.bAddress[5]);
    }

    return ipAddress;
}

public static string GetLocalIpAddressWhileRemote()
{
    var ipAddress = string.Empty;
    var processId = GetCurrentProcessId();
    var sessionId = 0;
    var hasFoundSessionId = ProcessIdToSessionId(processId, ref sessionId) != 0;
    if (hasFoundSessionId)
    {
        ipAddress = GetIpAddressFromSession(sessionId, IntPtr.Zero);
    }

    return ipAddress;
}

首先,您获取客户的processId 并使用它来获取sessionId。使用sessionId,您可以使用WTSQuerySessionInformationWTS_INFO_CLASS.WTSClientAddress 参数来获取会话IP 地址。我没有包含 WTS_INFO_CLASS 枚举,你仍然需要自己添加它才能工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-02-14
    • 1970-01-01
    • 2010-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-22
    • 1970-01-01
    相关资源
    最近更新 更多