1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 |
using System; using System.Collections; using System.Runtime.InteropServices; namespace ServerEnum { internal class Class1 { [DllImport("netapi32.dll", EntryPoint="NetServerEnum")] public static extern NERR NetServerEnum([MarshalAs(UnmanagedType.LPWStr)] string ServerName, int Level, out IntPtr BufPtr, int PrefMaxLen, ref int EntriesRead, ref int TotalEntries, SV_101_TYPES ServerType, [MarshalAs(UnmanagedType.LPWStr)] string Domain, int ResumeHandle); [DllImport("netapi32.dll", EntryPoint="NetApiBufferFree")] public static extern NERR NetApiBufferFree(IntPtr Buffer); [Flags] public enum SV_101_TYPES : uint { SV_TYPE_WORKSTATION = 0x00000001, SV_TYPE_SERVER = 0x00000002, SV_TYPE_SQLSERVER = 0x00000004, SV_TYPE_DOMAIN_CTRL = 0x00000008, SV_TYPE_DOMAIN_BAKCTRL = 0x00000010, SV_TYPE_TIME_SOURCE = 0x00000020, SV_TYPE_AFP = 0x00000040, SV_TYPE_NOVELL = 0x00000080, SV_TYPE_DOMAIN_MEMBER = 0x00000100, SV_TYPE_PRINTQ_SERVER = 0x00000200, SV_TYPE_DIALIN_SERVER = 0x00000400, SV_TYPE_XENIX_SERVER = 0x00000800, SV_TYPE_SERVER_UNIX = SV_TYPE_XENIX_SERVER, SV_TYPE_NT = 0x00001000, SV_TYPE_WFW = 0x00002000, SV_TYPE_SERVER_MFPN = 0x00004000, SV_TYPE_SERVER_NT = 0x00008000, SV_TYPE_POTENTIAL_BROWSER = 0x00010000, SV_TYPE_BACKUP_BROWSER = 0x00020000, SV_TYPE_MASTER_BROWSER = 0x00040000, SV_TYPE_DOMAIN_MASTER = 0x00080000, SV_TYPE_SERVER_OSF = 0x00100000, SV_TYPE_SERVER_VMS = 0x00200000, SV_TYPE_WINDOWS = 0x00400000, SV_TYPE_DFS = 0x00800000, SV_TYPE_CLUSTER_NT = 0x01000000, SV_TYPE_TERMINALSERVER = 0x02000000, SV_TYPE_CLUSTER_VS_NT = 0x04000000, SV_TYPE_DCE = 0x10000000, SV_TYPE_ALTERNATE_XPORT = 0x20000000, SV_TYPE_LOCAL_LIST_ONLY = 0x40000000, SV_TYPE_DOMAIN_ENUM = 0x80000000, SV_TYPE_ALL = 0xFFFFFFFF, } [StructLayout(LayoutKind.Sequential)] public struct SERVER_INFO_101 { [MarshalAs(UnmanagedType.U4)] public uint sv101_platform_id; [MarshalAs(UnmanagedType.LPWStr)] public string sv101_name; [MarshalAs(UnmanagedType.U4)] public uint sv101_version_major; [MarshalAs(UnmanagedType.U4)] public uint sv101_version_minor; [MarshalAs(UnmanagedType.U4)] public uint sv101_type; [MarshalAs(UnmanagedType.LPWStr)] public string sv101_comment; } public enum PLATFORM_ID : uint { PLATFORM_ID_DOS = 300, PLATFORM_ID_OS2 = 400, PLATFORM_ID_NT = 500, PLATFORM_ID_OSF = 600, PLATFORM_ID_VMS = 700, } public enum NERR { NERR_Success = 0, ERROR_ACCESS_DENIED = 5, ERROR_NOT_ENOUGH_MEMORY = 8, ERROR_BAD_NETPATH = 53, ERROR_NETWORK_BUSY = 54, ERROR_INVALID_PARAMETER = 87, ERROR_INVALID_LEVEL = 124, ERROR_MORE_DATA = 234, ERROR_EXTENDED_ERROR = 1208, ERROR_NO_NETWORK = 1222, ERROR_INVALID_HANDLE_STATE = 1609, ERROR_NO_BROWSER_SERVERS_FOUND = 6118, } public static ArrayList GetServerList(SV_101_TYPES type) { SERVER_INFO_101 si; IntPtr pInfo = IntPtr.Zero; int etriesread = 0; int totalentries = 0; ArrayList srvs = new ArrayList(); try { NERR err = NetServerEnum(null, 101, out pInfo, -1, ref etriesread, ref totalentries, type, null, 0); if ((err == NERR.NERR_Success || err == NERR.ERROR_MORE_DATA) && pInfo != IntPtr.Zero) { int ptr = pInfo.ToInt32(); for (int i = 0; i < etriesread; i++) { si = (SERVER_INFO_101) Marshal.PtrToStructure(new IntPtr(ptr), typeof (SERVER_INFO_101)); srvs.Add(si.sv101_name); ptr += Marshal.SizeOf(si); } } } catch (Exception) { } finally { if (pInfo != IntPtr.Zero) { NetApiBufferFree(pInfo); } } return (srvs); } [STAThread] static void Main() { Console.WriteLine("{0} WORKSTATION", new string('=', 10)); ArrayList list = GetServerList(SV_101_TYPES.SV_TYPE_WORKSTATION); foreach (string name in list) { Console.WriteLine(name); } Console.WriteLine("{0} UNIX", new string('=', 10)); list = GetServerList(SV_101_TYPES.SV_TYPE_SERVER_UNIX); foreach (string name in list) { Console.WriteLine(name); } Console.ReadLine(); } } } |
Создана следующая схема:
Сервер 1: Является виртуальным: на нем крутится Контроллер домена.
Сам сервер 1 вогнан в домен…
Сервер 2: Является дополнительным контроллером домена и виртуальным, на него прилетают репликации с первого сервака, еще он является
почтовым сервером…
Так же имеется лес подчиненных серверов
Имеется такая проблема, при отключении Сервера 1, клиенты не могут залогинится на подчиненные сервера… зайти на него под доменным
администратором я не могу! не пускает…(Отсутствуют серверы, которые могли бы обработать запрос на вход в
сеть)
Хотя в тоже время в сети есть второй контроллер домена, который является Глобальным каталогом…
Соответственно вопрос, почему так, и что надо дополнительно настроить, чтобы авторизация пользователей проходила и при отключенным первым
контроллером домена?
На всех компьютерах, в настройках DNS серверов, указаны адреса 1 контроллера домена и второго
DC1
C:Windowssystem32>ipconfig /all
Настройка протокола IP для Windows
Имя компьютера . . . . . . . . . : DC1
Основной DNS-суффикс . . . . . . : WWW.LOC
Тип узла. . . . . . . . . . . . . : Гибридный
IP-маршрутизация включена . . . . : Нет
WINS-прокси включен . . . . . . . : Нет
Порядок просмотра суффиксов DNS . : WWW.LOC
Ethernet adapter Подключение по локальной сети 3:
DNS-суффикс подключения . . . . . :
Описание. . . . . . . . . . . . . : HP Network Team #1
Физический адрес. . . . . . . . . : ****
DHCP включен. . . . . . . . . . . : Нет
Автонастройка включена. . . . . . : Да
IPv4-адрес. . . . . . . . . . . . : 192.168.1.14(Основной)
Маска подсети . . . . . . . . . . : 255.255.255.0
Основной шлюз. . . . . . . . . : 192.168.1.1
DNS-серверы. . . . . . . . . . . : 127.0.0.1
192.168.1.18
NetBios через TCP/IP. . . . . . . . : Включен
Туннельный адаптер Teredo Tunneling Pseudo-Interface:
Состояние среды. . . . . . . . : Среда передачи недоступна.
Туннельный адаптер isatap.{****}:
Состояние среды. . . . . . . . : Среда передачи недоступна.
DC2
C:Windowssystem32>ipconfig /all
Настройка протокола IP для Windows
Имя компьютера . . . . . . . . . : dc2
Основной DNS-суффикс . . . . . . : WWW.LOC
Тип узла. . . . . . . . . . . . . : Гибридный
IP-маршрутизация включена . . . . : Нет
WINS-прокси включен . . . . . . . : Нет
Порядок просмотра суффиксов DNS . : WWW.LOC
Ethernet adapter Подключение по локальной сети:
DNS-суффикс подключения . . . . . :
Описание. . . . . . . . . . . . . : Сетевое подключение Intel(R) PRO/1000 MT
Физический адрес. . . . . . . . . : ****
DHCP включен. . . . . . . . . . . : Нет
Автонастройка включена. . . . . . : Да
IPv4-адрес. . . . . . . . . . . . : 192.168.1.18(Основной)
Маска подсети . . . . . . . . . . : 255.255.255.0
Основной шлюз. . . . . . . . . : 192.168.1.1
DNS-серверы. . . . . . . . . . . : 192.168.1.14
192.168.1.18
NetBios через TCP/IP. . . . . . . . : Включен
Туннельный адаптер isatap.{****}:
Состояние среды. . . . . . . . : Среда передачи недоступна.
DNS-суффикс подключения . . . . . :
Описание. . . . . . . . . . . . . : Адаптер Microsoft
Физический адрес. . . . . . . . . : ****
DHCP включен. . . . . . . . . . . : Нет
Автонастройка включена. . . . . . : Да
Туннельный адаптер Teredo Tunneling Pseudo-Interface:
Состояние среды. . . . . . . . : Среда передачи недоступна.
DNS-суффикс подключения . . . . . :
Описание. . . . . . . . . . . . . : Teredo Tunneling Pseudo-Interface
Физический адрес. . . . . . . . . : ****
DHCP включен. . . . . . . . . . . : Нет
Автонастройка включена. . . . . . : Да
Туннельный адаптер 6TO4 Adapter:
DNS-суффикс подключения . . . . . :
Описание. . . . . . . . . . . . . : Адаптер Microsoft 6to4
Физический адрес. . . . . . . . . : ****
DHCP включен. . . . . . . . . . . : Нет
Автонастройка включена. . . . . . : Да
IPv6-адрес. . . . . . . . . . . . : 2002:d997:8c8f::d997:8c8f(Основной)
Основной шлюз. . . . . . . . . :
DNS-серверы. . . . . . . . . . . : 10.48.1.14
10.48.1.18
NetBios через TCP/IP. . . . . . . . : Отключен
DC1
C:Windowssystem32>netdom query fsmo
Хозяин схемы DC1.WWW.LOC
Хозяин именования доменов DC1.WWW.LOC
PDC DC1.WWW.LOC
Диспетчер пула RID DC1.WWW.LOC
Хозяин инфраструктуры DC1.WWW.LOC
Команда выполнена успешно.
DC2
C:Windowssystem32>netdom query fsmo
Хозяин схемы DC1.WWW.LOC
Хозяин именования доменов DC1.WWW.LOC
PDC DC1.WWW.LOC
Диспетчер пула RID DC1.WWW.LOC
Хозяин инфраструктуры DC1.WWW.LOC
Команда выполнена успешно.
UID | title | description | helpviewer_keywords | old-location | tech.root | ms.assetid | ms.date | ms.keywords | req.header | req.include-header | req.target-type | req.target-min-winverclnt | req.target-min-winversvr | req.kmdf-ver | req.umdf-ver | req.ddi-compliance | req.unicode-ansi | req.idl | req.max-support | req.namespace | req.assembly | req.type-library | req.lib | req.dll | req.irql | targetos | req.typenames | req.redist | ms.custom | f1_keywords | dev_langs | topic_type | api_type | api_location | api_name | |||||||||||||||||||||||||||||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
NF:lmserver.NetServerEnum |
NetServerEnum function (lmserver.h) |
The NetServerEnum function lists all servers of the specified type that are visible in a domain. |
|
netmgmtnetserverenum.htm |
NetMgmt |
10012a87-805e-4817-9f09-9e5632b1fa09 |
12/05/2018 |
100, 101, NetServerEnum, NetServerEnum function [Network Management], SV_TYPE_AFP, SV_TYPE_ALL, SV_TYPE_ALTERNATE_XPORT, SV_TYPE_BACKUP_BROWSER, SV_TYPE_CLUSTER_NT, SV_TYPE_CLUSTER_VS_NT, SV_TYPE_DCE, SV_TYPE_DFS, SV_TYPE_DIALIN_SERVER, SV_TYPE_DOMAIN_BAKCTRL, SV_TYPE_DOMAIN_CTRL, SV_TYPE_DOMAIN_ENUM, SV_TYPE_DOMAIN_MASTER, SV_TYPE_DOMAIN_MEMBER, SV_TYPE_LOCAL_LIST_ONLY, SV_TYPE_MASTER_BROWSER, SV_TYPE_NOVELL, SV_TYPE_NT, SV_TYPE_POTENTIAL_BROWSER, SV_TYPE_PRINTQ_SERVER, SV_TYPE_SERVER, SV_TYPE_SERVER_MFPN, SV_TYPE_SERVER_NT, SV_TYPE_SERVER_OSF, SV_TYPE_SERVER_UNIX, SV_TYPE_SERVER_VMS, SV_TYPE_SQLSERVER, SV_TYPE_TERMINALSERVER, SV_TYPE_TIME_SOURCE, SV_TYPE_WFW, SV_TYPE_WINDOWS, SV_TYPE_WORKSTATION, SV_TYPE_XENIX_SERVER, _win32_netserverenum, lmserver/NetServerEnum, netmgmt.netserverenum |
lmserver.h |
Lm.h |
Windows |
Windows 2000 Professional [desktop apps only] |
Windows 2000 Server [desktop apps only] |
Netapi32.lib |
Netapi32.dll |
Windows |
19H1 |
|
c++ |
|
DllExport |
|
NetServerEnum |
NetServerEnum function
-description
The
NetServerEnum function lists all servers of the specified type that are visible in a domain.
-parameters
-param servername [in, optional]
Reserved; must be NULL.
-param level [in]
The information level of the data requested. This parameter can be one of the following values.
Value | Meaning |
---|---|
|
Return server names and platform information. The bufptr parameter points to an array of SERVER_INFO_100 structures. |
|
Return server names, types, and associated data. The bufptr parameter points to an array of SERVER_INFO_101 structures. |
-param bufptr [out]
A pointer to the buffer that receives the data. The format of this data depends on the value of the level parameter. This buffer is allocated by the system and must be freed using the
NetApiBufferFree function. Note that you must free the buffer even if the function fails with ERROR_MORE_DATA.
-param prefmaxlen [in]
The preferred maximum length of returned data, in bytes. If you specify MAX_PREFERRED_LENGTH, the function allocates the amount of memory required for the data. If you specify another value in this parameter, it can restrict the number of bytes that the function returns. If the buffer size is insufficient to hold all entries, the function returns ERROR_MORE_DATA. For more information, see
Network Management Function Buffers and
Network Management Function Buffer Lengths.
-param entriesread [out]
A pointer to a value that receives the count of elements actually enumerated.
-param totalentries [out]
A pointer to a value that receives the total number of visible servers and workstations on the network. Note that applications should consider this value only as a hint.
-param servertype [in]
A value that filters the server entries to return from the enumeration. This parameter can be a combination of the following values defined in the Lmserver.h header file.
Value | Meaning |
---|---|
|
All workstations. |
|
All computers that run the Server service. |
|
Any server that runs an instance of Microsoft SQL Server. |
|
A server that is primary domain controller. |
|
Any server that is a backup domain controller. |
|
Any server that runs the Timesource service. |
|
Any server that runs the Apple Filing Protocol (AFP) file service. |
|
Any server that is a Novell server. |
|
Any computer that is LAN Manager 2.x domain member. |
|
Any computer that shares a print queue. |
|
Any server that runs a dial-in service. |
|
Any server that is a Xenix server. |
|
Any server that is a UNIX server. This is the same as the SV_TYPE_XENIX_SERVER. |
|
A workstation or server. |
|
Any computer that runs Windows for Workgroups. |
|
Any server that runs the Microsoft File and Print for NetWare service. |
|
Any server that is not a domain controller. |
|
Any computer that can run the browser service. |
|
A computer that runs a browser service as backup. |
|
A computer that runs the master browser service. |
|
A computer that runs the domain master browser. |
|
A computer that runs OSF/1. |
|
A computer that runs Open Virtual Memory System (VMS). |
|
A computer that runs Windows. |
|
A computer that is the root of Distributed File System (DFS) tree. |
|
Server clusters available in the domain. |
|
A server running the Terminal Server service. |
|
Cluster virtual servers available in the domain.
Windows 2000: This value is not supported. |
|
A computer that runs IBM Directory and Security Services (DSS) or equivalent. |
|
A computer that over an alternate transport. |
|
Any computer maintained in a list by the browser. See the following Remarks section. |
|
The primary domain. |
|
All servers. This is a convenience that will return all possible servers. |
-param domain [in, optional]
A pointer to a constant string that specifies the name of the domain for which a list of servers is to be returned. The domain name must be a NetBIOS domain name (for example, microsoft).
The NetServerEnum function does not support DNS-style names (for example, microsoft.com).
If this parameter is NULL, the primary domain is implied.
-param resume_handle [in, out, optional]
Reserved; must be set to zero.
-returns
If the function succeeds, the return value is NERR_Success.
If the function fails, the return value can be one of the following error codes:
Return code/value | Description |
---|---|
|
Access was denied. |
|
The parameter is incorrect. |
|
More entries are available. Specify a large enough buffer to receive all entries. |
|
No browser servers found. |
|
The request is not supported. |
|
A remote error occurred with no data returned by the server. |
|
The server service is not started. |
|
The service has not been started. |
|
The Workstation service has not been started. The local workstation service is used to communicate with a downlevel remote server. |
-remarks
The
NetServerEnum function is used to list all servers of the specified type that are visible in a domain. For example, an application can call
NetServerEnum to list all domain controllers only or all servers that run instances of SQL server only.
An application combine the bit masks for various server types in the servertype parameter to list several types. For example, a value of SV_TYPE_WORKSTATION | SVTYPE_SERVER (0x00000003) combines the bit masks for SV_TYPE_WORKSTATION (0x00000001) and SV_TYPE_SERVER (0x00000002).
If you require more information for a specific server, call the
WNetEnumResource function.
No special group membership is required to successfully execute the
NetServerEnum function.
If you specify the value SV_TYPE_LOCAL_LIST_ONLY, the
NetServerEnum function returns the list of servers that the browser maintains internally. This has meaning only on the master browser (or on a computer that has been the master browser in the past). The master browser is the computer that currently has rights to determine which computers can be servers or workstations on the network.
If there are no servers found that match the types specified in the servertype parameter, the
NetServerEnum function returns the bufptr parameter as NULL and DWORD values pointed to by the entriesread and totalentries parameters are set to zero.
The
NetServerEnum function depends on the browser service being installed and running. If no browser servers are found, then NetServerEnum fails with ERROR_NO_BROWSER_SERVERS_FOUND.
If you are programming for Active Directory, you may be able to call certain Active Directory Service Interface (ADSI) methods to achieve the same function you can achieve by calling the network management server functions. For more information, see
IADsComputer.
Examples
The following code sample demonstrates how to list all servers that are visible in a domain with a call to the
NetServerEnum function. The sample calls
NetServerEnum, specifying information level 101 (
SERVER_INFO_101). If any servers are found, the sample code loops through the entries and prints the retrieved data. If the server is a domain controller, it identifies the server as either a primary domain controller (PDC) or a backup domain controller (BDC). The sample also prints the total number of entries available and a hint about the number of entries actually enumerated, warning the user if all entries were not enumerated. Finally, the sample frees the memory allocated for the information buffer.
#ifndef UNICODE #define UNICODE #endif #pragma comment(lib, "netapi32.lib") #include <stdio.h> #include <assert.h> #include <windows.h> #include <lm.h> int wmain(int argc, wchar_t * argv[]) { LPSERVER_INFO_101 pBuf = NULL; LPSERVER_INFO_101 pTmpBuf; DWORD dwLevel = 101; DWORD dwPrefMaxLen = MAX_PREFERRED_LENGTH; DWORD dwEntriesRead = 0; DWORD dwTotalEntries = 0; DWORD dwTotalCount = 0; DWORD dwServerType = SV_TYPE_SERVER; // all servers DWORD dwResumeHandle = 0; NET_API_STATUS nStatus; LPWSTR pszServerName = NULL; LPWSTR pszDomainName = NULL; DWORD i; if (argc > 2) { fwprintf(stderr, L"Usage: %s [DomainName]n", argv[0]); exit(1); } // The request is not for the primary domain. // if (argc == 2) pszDomainName = argv[1]; // // Call the NetServerEnum function to retrieve information // for all servers, specifying information level 101. // nStatus = NetServerEnum(pszServerName, dwLevel, (LPBYTE *) & pBuf, dwPrefMaxLen, &dwEntriesRead, &dwTotalEntries, dwServerType, pszDomainName, &dwResumeHandle); // // If the call succeeds, // if ((nStatus == NERR_Success) || (nStatus == ERROR_MORE_DATA)) { if ((pTmpBuf = pBuf) != NULL) { // // Loop through the entries and // print the data for all server types. // for (i = 0; i < dwEntriesRead; i++) { assert(pTmpBuf != NULL); if (pTmpBuf == NULL) { fprintf(stderr, "An access violation has occurredn"); break; } printf("tPlatform: %dn", pTmpBuf->sv101_platform_id); wprintf(L"tName: %sn", pTmpBuf->sv101_name); printf("tVersion: %d.%dn", pTmpBuf->sv101_version_major, pTmpBuf->sv101_version_minor); printf("tType: %d", pTmpBuf->sv101_type); // // Check to see if the server is a domain controller; // if so, identify it as a PDC or a BDC. // if (pTmpBuf->sv101_type & SV_TYPE_DOMAIN_CTRL) wprintf(L" (PDC)"); else if (pTmpBuf->sv101_type & SV_TYPE_DOMAIN_BAKCTRL) wprintf(L" (BDC)"); printf("n"); // // Also print the comment associated with the server. // wprintf(L"tComment: %snn", pTmpBuf->sv101_comment); pTmpBuf++; dwTotalCount++; } // Display a warning if all available entries were // not enumerated, print the number actually // enumerated, and the total number available. if (nStatus == ERROR_MORE_DATA) { fprintf(stderr, "nMore entries available!!!n"); fprintf(stderr, "Total entries: %d", dwTotalEntries); } printf("nEntries enumerated: %dn", dwTotalCount); } else { printf("No servers were foundn"); printf("The buffer (bufptr) returned was NULLn"); printf(" entriesread: %dn", dwEntriesRead); printf(" totalentries: %dn", dwEntriesRead); } } else fprintf(stderr, "NetServerEnum failed with error: %dn", nStatus); // // Free the allocated buffer. // if (pBuf != NULL) NetApiBufferFree(pBuf); return 0; }
-see-also
NetQueryDisplayInformation
NetServerDiskEnum
Network
Management Functions
Network Management
Overview
SERVER_INFO_100
SERVER_INFO_101
Server
Functions
Подскажите пожалуйста в чем может быть проблема при обращении к NetServerEnum.
Код честно скопирован множество раз с разных сайтов и из msdn.
Как только доходит до строки обращения к внешней функции (выделено красным цветом) возникает ошибка:
An unhandled exception of type ‘System.NullReferenceException’ occurred in Test.exe
Additional information: Object reference not set to an instance of an object.
По честному отсмотрел кучу постов о том, как получить список машин в домене, но такой проблемы ни у кого не возникало.
Код прилагается, спасибо за помощь
Option Explicit Off
Imports System.Runtime.InteropServices
Public Class Form1
Inherits System.Windows.Forms.Form
Const ERROR_SUCCESS = 0
Const ERROR_MORE_DATA = 234
Const SV_TYPE_WORKSTATION = &H8
Const SIZE_SI_101 = 24
Public Structure SERVER_INFO_100
Public sv100_platform_id As Long
Public sv100_name As Long
End Structure
Public Enum SV_101_TYPES
SV_TYPE_WORKSTATION = &H1
SV_TYPE_SERVER = &H2
SV_TYPE_ALL = &H0
End Enum
Public Structure SERVER_INFO_101
Public dwPlatformId As Long
Public lpszServerName As String
Public dwVersionMajor As Long
Public dwVersionMinor As Long
Public dwType As Long
Public lpszComment As Long
End Structure
Declare Auto Function NetServerEnum Lib «netapi32.dll» (ByVal servername As String, _
ByVal level As Long, _
ByRef buffer As Long, _
ByVal prefmaxlen As Long, _
ByRef entriesread As Long, _
ByRef totalentries As Long, _
ByVal ByValservertype As System.Runtime.InteropServices.UnmanagedType, _
ByVal domain As String, _
ByRef resumehandle As Long) As Long
Declare Auto Function NetApiBufferFree Lib «netapi32.dll» ( _
ByVal BufPtr As Long) As Long
Declare Sub RtlMoveMemory Lib «KERNEL32» ( _
ByRef hpvDest As SERVER_INFO_101, _
ByVal hpvSource As Long, _
ByVal cbCopy As Long)
Declare Function lstrcpyW Lib «KERNEL32» ( _
ByVal lpszDest As String, _
ByVal lpszSrc As Long) As Long
Private Function PointerToString(ByVal lpszString As Long) As String
Dim intPos As Integer
Dim lpszStr2 As String
Dim nRes As Long
Dim lpszStr1 As New String(«*»c, 1000)
nRes = lstrcpyW(lpszStr1, lpszString)
lpszStr2 = lpszStr1
intPos = InStr(lpszStr2, Chr(0)) — 1
PointerToString = Microsoft.VisualBasic.Left(lpszStr2, intPos)
End Function
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim pszTemp As String
Dim pszServer As String
Dim pszDomain As String
Dim nLevel As Long, i As Long, BufPtr As Long, TempBufPtr As Long
Dim nPrefMaxLen As Long, nEntriesRead As Long, nTotalEntries As Long
Dim nServerType As Long, nResumeHandle As Long, nRes As Long
Dim ServerInfo As SERVER_INFO_101
Dim sWSName As String
pszServer = Nothing
pszDomain = Nothing
nLevel = 101
BufPtr = 0
nPrefMaxLen = -1
nEntriesRead = 0
nTotalEntries = 0
nServerType = SV_TYPE_WORKSTATION
nResumeHandle = IntPtr.Zero.ToInt32
Do
nRes = NetServerEnum(«», _
nLevel, _
BufPtr, _
nPrefMaxLen, _
nEntriesRead, _
nTotalEntries, _
SV_101_TYPES.SV_TYPE_SERVER, _
«», _
nResumeHandle)
If ((nRes = ERROR_SUCCESS) Or (nRes = ERROR_MORE_DATA)) And _
(nEntriesRead > 0) Then
TempBufPtr = BufPtr
For i = 1 To nEntriesRead
RtlMoveMemory(ServerInfo, TempBufPtr, SIZE_SI_101)
sWSName = PointerToString(ServerInfo.lpszServerName)
TempBufPtr = TempBufPtr + SIZE_SI_101
Next i
Else
MsgBox(«NetServerEnum failed: » & nRes)
End If
NetApiBufferFree(BufPtr)
Loop While nEntriesRead < nTotalEntries
End Sub
End Class
S>Подскажите пожалуйста в чем может быть проблема при обращении к NetServerEnum.
Разбираться лениво, но вот рабочий кусок кода
отсюда
:
using System;
using System.Collections;
using System.Runtime.InteropServices;
namespace ServerEnum
{
internal class Class1
{
[DllImport("netapi32.dll", EntryPoint="NetServerEnum")]
public static extern NERR NetServerEnum (
[MarshalAs(UnmanagedType.LPWStr)] string ServerName,
int Level, out IntPtr BufPtr, int PrefMaxLen,
ref int EntriesRead, ref int TotalEntries,
SV_101_TYPES ServerType,
[MarshalAs(UnmanagedType.LPWStr)] string Domain,
int ResumeHandle);
[DllImport("netapi32.dll", EntryPoint="NetApiBufferFree")]
public static extern NERR NetApiBufferFree (IntPtr Buffer);
//
// типы серверов
//
[Flags]
public enum SV_101_TYPES : uint
{
SV_TYPE_WORKSTATION = 0x00000001,
SV_TYPE_SERVER = 0x00000002,
SV_TYPE_SQLSERVER = 0x00000004,
SV_TYPE_DOMAIN_CTRL = 0x00000008,
SV_TYPE_DOMAIN_BAKCTRL = 0x00000010,
SV_TYPE_TIME_SOURCE = 0x00000020,
SV_TYPE_AFP = 0x00000040,
SV_TYPE_NOVELL = 0x00000080,
SV_TYPE_DOMAIN_MEMBER = 0x00000100,
SV_TYPE_PRINTQ_SERVER = 0x00000200,
SV_TYPE_DIALIN_SERVER = 0x00000400,
SV_TYPE_XENIX_SERVER = 0x00000800,
SV_TYPE_SERVER_UNIX = SV_TYPE_XENIX_SERVER,
SV_TYPE_NT = 0x00001000,
SV_TYPE_WFW = 0x00002000,
SV_TYPE_SERVER_MFPN = 0x00004000,
SV_TYPE_SERVER_NT = 0x00008000,
SV_TYPE_POTENTIAL_BROWSER = 0x00010000,
SV_TYPE_BACKUP_BROWSER = 0x00020000,
SV_TYPE_MASTER_BROWSER = 0x00040000,
SV_TYPE_DOMAIN_MASTER = 0x00080000,
SV_TYPE_SERVER_OSF = 0x00100000,
SV_TYPE_SERVER_VMS = 0x00200000,
SV_TYPE_WINDOWS = 0x00400000,
SV_TYPE_DFS = 0x00800000,
SV_TYPE_CLUSTER_NT = 0x01000000,
SV_TYPE_TERMINALSERVER = 0x02000000,
SV_TYPE_CLUSTER_VS_NT = 0x04000000,
SV_TYPE_DCE = 0x10000000,
SV_TYPE_ALTERNATE_XPORT = 0x20000000,
SV_TYPE_LOCAL_LIST_ONLY = 0x40000000,
SV_TYPE_DOMAIN_ENUM = 0x80000000,
SV_TYPE_ALL = 0xFFFFFFFF,
}
[StructLayout(LayoutKind.Sequential)]
public struct SERVER_INFO_101
{
[MarshalAs(UnmanagedType.U4)] public uint sv101_platform_id;
[MarshalAs(UnmanagedType.LPWStr)] public string sv101_name;
[MarshalAs(UnmanagedType.U4)] public uint sv101_version_major;
[MarshalAs(UnmanagedType.U4)] public uint sv101_version_minor;
[MarshalAs(UnmanagedType.U4)] public uint sv101_type;
[MarshalAs(UnmanagedType.LPWStr)] public string sv101_comment;
}
//
// оперционная система
//
public enum PLATFORM_ID : uint
{
PLATFORM_ID_DOS = 300,
PLATFORM_ID_OS2 = 400,
PLATFORM_ID_NT = 500,
PLATFORM_ID_OSF = 600,
PLATFORM_ID_VMS = 700,
}
//
// список ошибок, возвращаемых NetServerEnum
//
public enum NERR
{
NERR_Success = 0, // Успех
ERROR_ACCESS_DENIED = 5,
ERROR_NOT_ENOUGH_MEMORY = 8,
ERROR_BAD_NETPATH = 53,
ERROR_NETWORK_BUSY = 54,
ERROR_INVALID_PARAMETER = 87,
ERROR_INVALID_LEVEL = 124,
ERROR_MORE_DATA = 234,
ERROR_EXTENDED_ERROR = 1208,
ERROR_NO_NETWORK = 1222,
ERROR_INVALID_HANDLE_STATE = 1609,
ERROR_NO_BROWSER_SERVERS_FOUND = 6118,
}
public static ArrayList GetServerList(SV_101_TYPES type)
{
SERVER_INFO_101 si;
IntPtr pInfo = IntPtr.Zero;
int etriesread = 0;
int totalentries = 0;
ArrayList srvs = new ArrayList();
try
{
NERR err = NetServerEnum(null, 101, out pInfo, -1,
ref etriesread, ref totalentries, type, null, 0);
if ((err == NERR.NERR_Success ||
err == NERR.ERROR_MORE_DATA) &&
pInfo != IntPtr.Zero)
{
int ptr = pInfo.ToInt32();
for (int i = 0; i < etriesread; i++)
{
si = (SERVER_INFO_101) Marshal.PtrToStructure(
new IntPtr(ptr), typeof (SERVER_INFO_101));
srvs.Add(si.sv101_name); // добавляем имя
// сервера в список
ptr += Marshal.SizeOf(si);
}
}
}
catch (Exception)
{
}
finally
{ // освобождаем выделенную память
if (pInfo != IntPtr.Zero)
{
NetApiBufferFree(pInfo);
}
}
return (srvs);
}
[STAThread]
static void Main()
{
Console.WriteLine("{0} WORKSTATION", new string('=', 10));
ArrayList list =
GetServerList(SV_101_TYPES.SV_TYPE_WORKSTATION);
foreach (string name in list)
{
Console.WriteLine(name);
}
Console.WriteLine("{0} UNIX", new string('=', 10));
list = GetServerList(SV_101_TYPES.SV_TYPE_SERVER_UNIX);
foreach (string name in list)
{
Console.WriteLine(name);
}
}
}
}