C# winform系统下 远程桌面连接时取得客户端的IP

最近在遇到个系统,是移动终端A(可以把它看成普通电脑)通过远程桌面连接服务器B调用B上的程序,如何得到终端A的IP?

查了好多资料,也请教了高手。从以前一个VB程序中的方法改成C#的方法。

基本思路是API 调用wtsapi32.dll来实现。

废话不多说,上代码。。。

using System;
using System.Runtime;
using System.Runtime.InteropServices;
using System.Text;

namespace ArrivalInspection
{
 /// <summary>
 /// </summary>
 public class csClientIP
 {
  [DllImport("wtsapi32", CharSet = CharSet.Auto, SetLastError = true)]
  private static extern bool WTSEnumerateSessions(int hServer, int Reserved, int Version, ref long ppSessionInfo, ref int pCount);


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

  
  [DllImport("wtsapi32.dll")]
  public static extern bool WTSLogoffSession(int hServer, long SessionId, bool bWait);
  [DllImport("Wtsapi32.dll")]
  public static extern bool WTSQuerySessionInformation(
   System.IntPtr hServer, int sessionId, WTSInfoClass wtsInfoClass, out StringBuilder ppBuffer, out int pBytesReturned);
  
  [DllImport("Wtsapi32.dll")]
  public static extern bool WTSQuerySessionInformation(
   System.IntPtr hServer, int sessionId, WTSInfoClass wtsInfoClass, out byte[] ppBuffer, out int pBytesReturned);


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

  /**/
  /// <summary>
  /// The WTS_CONNECTSTATE_CLASS enumeration type contains INT values that indicate the connection state of a Terminal Services session.
  /// </summary>
  public enum WTS_CONNECTSTATE_CLASS
  {
   WTSActive,
   WTSConnected,
   WTSConnectQuery,
   WTSShadow,
   WTSDisconnected,
   WTSIdle,
   WTSListen,
   WTSReset,
   WTSDown,
   WTSInit,
  }


  /**/
  /// <summary>
  /// The WTS_SESSION_INFO structure contains information about a client session on a terminal server.
  /// if the WTS_SESSION_INFO.SessionID==0, it means that the SESSION is the local logon user's session.
  /// </summary>
  public struct WTS_SESSION_INFO
  {
   public int SessionID;
   [MarshalAs(UnmanagedType.LPTStr)]
   public string pWinStationName;
   public WTS_CONNECTSTATE_CLASS state;
  }

  /**/
  /// <summary>
  /// The SessionEnumeration function retrieves a list of WTS_SESSION_INFO on a current terminal server.
  /// </summary>
  /// <returns>a list of WTS_SESSION_INFO on a current terminal server</returns>
  public static WTS_SESSION_INFO[] SessionEnumeration()
  {
   //Set handle of terminal server as the current terminal server
   int hServer = 0;
   bool RetVal;
   long lpBuffer = 0;
   int Count = 0;
   long p;
   WTS_SESSION_INFO Session_Info = new WTS_SESSION_INFO();
   WTS_SESSION_INFO[] arrSessionInfo;
   RetVal = WTSEnumerateSessions(hServer, 0, 1, ref lpBuffer, ref Count);
   arrSessionInfo = new WTS_SESSION_INFO[0];
   if (RetVal)
   {
    arrSessionInfo = new WTS_SESSION_INFO[Count];
    int i;
    p = lpBuffer;
    for (i = 0; i < Count; i++)
    {
     arrSessionInfo[i] = (WTS_SESSION_INFO)Marshal.PtrToStructure(new IntPtr(p), Session_Info.GetType());
     p += Marshal.SizeOf(Session_Info.GetType());
    }
    WTSFreeMemory(new IntPtr(lpBuffer));
   }
   else
   {
    //Insert Error Reaction Here
   }
   return arrSessionInfo;
  }

 }
}

////上面是写成了一个类,下面是取得客户端IP的方法

private string getClientIP()
  {
   csClientIP.WTS_SESSION_INFO[] pSessionInfo = csClientIP.SessionEnumeration();
   try
   {
    int count = 0;
    IntPtr buffer = IntPtr.Zero;
    StringBuilder sb = new StringBuilder();    
    bool bsuccess = csClientIP.WTSQuerySessionInformation(IntPtr.Zero, -1, csClientIP.WTSInfoClass.WTSClientName, out sb, out count);
    string strIP = "";
    if (bsuccess)
    {
     string strName = sb.ToString().Trim();
     if(strName == "")
     {
      strIP = "";
     }
     else
     {
      IPHostEntry ipEntry = Dns.GetHostByName(strName);
      IPAddress[] IpAddr = ipEntry.AddressList;     
      for (int i=0;i<IpAddr.Length;i++)
      {
       strIP = strIP + IpAddr[i].ToString();
      }
     }     
    }
    return strIP;
   }
   catch (Exception ex)
   {
    throw ex;
   }
  }

猜你喜欢

转载自blog.csdn.net/summonyyq/article/details/5649747
今日推荐