Thursday, November 15, 2007

Search the network for the presence of a machine

Check out the following function, which can be used to check whether a given machine is present in the primary domain:

// Include Netapi32.lib in the project settings

#include

BOOL FindServer (const CString& rcsTarget )

{

NET_API_STATUS nas ;

NET_DISPLAY_MACHINE * pndm;

SERVER_INFO_101 * pSI_101 ;

DWORD dwEntriesRead;

DWORD dwTotalEntries;

DWORD dwRetVal = ERROR_SUCCESS;

DWORD dwNdmCount;

int iCount;

char szServer [64];

WCHAR wcServer [64];

CString csServer;

CString csTarget = rcsTarget;

BOOL bFound = FALSE;

nas = NetServerEnum (NULL,

101,

(LPBYTE*)&pSI_101,

MAX_PREFERRED_LENGTH,

&dwEntriesRead,

&dwTotalEntries,

SV_TYPE_SERVER, // type you're looking for.

NULL,

0);

if (nas == NERR_Success)

{

TRACE( "NetServerEnum found %u server(s)\n", dwEntriesRead);

for (iCount=0; iCount<(int)dwEntriesRead; iCount++)

{

WideCharToMultiByte (CP_ACP,

WC_COMPOSITECHECK,

(LPCWSTR)(pSI_101[iCount].sv101_name),

-1,

szServer,

sizeof(szServer),

NULL,

NULL);

TRACE( szServer );

TRACE( _T( "\n") );

csServer = szServer;

csServer.MakeUpper();

csTarget.MakeUpper();

if (csServer == csTarget)

{

// The browse info will continue to report machines

// for ages after they've been switched off, so try to

// talk direct to the machine.

wcscpy (wcServer, L"\\\\");

wcscat (wcServer, (LPCWSTR)(pSI_101[iCount].sv101_name));

nas = NetQueryDisplayInformation (wcServer,

2,

0,

1,

sizeof(NET_DISPLAY_MACHINE),

&dwNdmCount,

(PVOID*)&pndm);

switch (nas)

{

case NERR_Success:

case ERROR_MORE_DATA:

bFound = TRUE;

break;

default:

TRACE( "NQDI gave error %u\n", nas);

dwRetVal = nas;

break;

}

NetApiBufferFree ((PVOID)pndm);

if (bFound)

break;

}

}

NetApiBufferFree (pSI_101);

}

return bFound;

}

No comments: