ch7_07.cs

来自「《c#技术内幕代码》」· CS 代码 · 共 87 行

CS
87
字号
using System;
using System.Runtime.InteropServices;

class CH7_7
{
	public enum ServerTypeEnum
	{
	    steNone = 0,
	    steWorkstation = 0x00000001,
	    steAll = 0x00000002,
	    steSQLServer = 0x00000004,
	    steDomainController = 0x00000008
	}
	
	[sysimport(dll="netapi32.dll")]
	private static extern void NetApiBufferFree([marshal(UnmanagedType.U4)]uint bufptr);
	
	[sysimport(dll="netapi32.dll")] 
	unsafe private static extern uint NetServerEnum([marshal(UnmanagedType.LPWStr)] string ServerName, 
		uint level,
		[marshal(UnmanagedType.LPVoid)]uint* bufptr,
		uint prefmaxlen,
		ref uint entriesread,
		ref uint totalentries,
		uint servertype,
		[marshal(UnmanagedType.LPWStr)] string domain, 
		uint resume_handle);
	
	[System.Runtime.InteropServices.StructLayoutAttribute (LayoutKind.Sequential, CharSet=CharSet.Auto)]
	public struct SERVER_INFO_101 
	{ 
	    public int dwPlatformID; 
	    public int lpszServerName;
	    public int dwVersionMajor; 
	    public int dwVersionMinor; 
	    public int dwType; 
	    public int lpszComment;
	}

	public static void ListServers(string domain)
	{
	    string servername = null;
	    uint level = 101, prefmaxlen = 0xFFFFFFFF, entriesread = 0, 
	            totalentries = 0, 
	            resume_handle = 0; 
            ServerTypeEnum _ServerType = ServerTypeEnum.steAll;
	    
	    unsafe
	    {    
		//get a pointer to the server info structure
		SERVER_INFO_101* si = null;
		SERVER_INFO_101* pTmp;    
	
		uint nRes = NetServerEnum(servername, level, 
			(uint *) &si, prefmaxlen, ref entriesread, ref totalentries, 
			(uint)_ServerType, domain, resume_handle);
			
		if (nRes == 0)
		{
		    if ((pTmp = si) != null)    
		    {
			for (int i = 0; i < entriesread; i++)    
			{
			    try
			    {
				Console.WriteLine(Marshal.PtrToStringAuto(pTmp->lpszServerName));
			    }
			    catch (Exception e)
			    {
				Console.WriteLine(e.Message) ;
			    }
			    pTmp++;        
			}
		    }
		}
		NetApiBufferFree((uint)si);
	    }             
	} 
	
        public static void Main(String[] args)
	{
	   if ( args.Length > 0 )
  	      ListServers( args[0] );
	}
}
 

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?