네트워크 리소스에 대한 정보 검색

리소스를 소유하는 네트워크 공급자를 식별하기 위해 애플리케이션은 다음 코드 샘플에 설명된 대로 WNetGetResourceInformation 함수를 호출할 수 있습니다.

다음 샘플은 서버 이름을 매개 변수로 사용하고 해당 서버에 대한 정보를 반환하는 함수(CheckServer)입니다. 먼저 함수는 ZeroMemory 함수를 호출하여 메모리 블록의 내용을 0으로 초기화합니다. 그런 다음 샘플은 WNetGetResourceInformation 함수를 호출하여 NETRESOURCE 구조만 보유할 수 있을 만큼 큰 버퍼를 지정합니다. 루틴에는 이 크기의 버퍼가 NETRESOURCE 구조체의 멤버가 가리키는 가변 길이 문자열을 보유하기에 충분하지 않은 경우를 처리하는 오류 처리가 포함됩니다. 이 오류가 발생하면 샘플에서 충분한 메모리를 할당하고 WNetGetResourceInformation을 다시 호출합니다. 마지막으로 샘플은 할당된 메모리를 해제합니다.

샘플에서는 pszServer 매개 변수가 로컬 컴퓨터의 네트워크 공급자 중 하나가 인식하는 서버 이름을 가리킨다고 가정합니다.

#include <Windows.h>
#include <Winnetwk.h >

// Need to link with Mpr.lib
#pragma comment(lib, "Mpr.lib")
//
// Verify a server on the network. 
//
DWORD
CheckServer( LPTSTR pszServer )
{  
    DWORD dwBufferSize = sizeof(NETRESOURCE);
    LPBYTE lpBuffer;                  // buffer
    NETRESOURCE nr;
    LPTSTR pszSystem = NULL;          // variable-length strings

    //
    // Set the block of memory to zero; then initialize
    // the NETRESOURCE structure. 
    //
    ZeroMemory(&nr, sizeof(nr));

    nr.dwScope       = RESOURCE_GLOBALNET;
    nr.dwType        = RESOURCETYPE_ANY;
    nr.lpRemoteName  = pszServer;

    //
    // First call the WNetGetResourceInformation function with 
    // memory allocated to hold only a NETRESOURCE structure. This 
    // method can succeed if all the NETRESOURCE pointers are NULL.
    // If the call fails because the buffer is too small, allocate
    // a larger buffer.
    //
    lpBuffer = (LPBYTE) malloc( dwBufferSize );
    if (lpBuffer == NULL) 
        return FALSE;

    while ( WNetGetResourceInformation(&nr, lpBuffer, &dwBufferSize, 
                &pszSystem) == ERROR_MORE_DATA)
    {
        lpBuffer = (LPBYTE) realloc(lpBuffer, dwBufferSize);
    }

    // Process the contents of the NETRESOURCE structure and the
    // variable-length strings in lpBuffer and set dwValue. When
    // finished, free the memory.

    free(lpBuffer);

    return TRUE;
}