Platform SDK: Active Directory, ADSI, and Directory Services

Example Code for an RPC Client Locating a Server

The following code fragment locates a server with the example RPC service:

    //Begin the import. We explicitly start with the a known
    //entry, "ExampleRpcServiceEntry". The interface we are
    //looking for is defined by RpcExample_v1_0_s_ifspec, which 
    //is generated by MIDL. 
 
    status = RpcNsBindingImportBegin(RPC_C_NS_SYNTAX_DCE,
                                     (TCHAR *)&szEntryName,
                                     RpcExample_v1_0_c_ifspec,
                                     NULL,
                                     &hNs);
 
    //Abandon if we cannot find anything or get any errors.
    if (status != RPC_S_OK)
        return;
 
    //Now acquire the first available binding handle. In this
    //example, implicit handles are used: the implicit handle
    //"RpcExample_IfHandle" is generated by MIDL and defined in the 
    //MIDL-generated include file RpcExample.H.
 
    //Loop through the bindings and try handles
    //until one works.
 
    while (status != RPC_S_NO_MORE_BINDINGS) {
        status = RpcNsBindingImportNext(hNs,
                                        &RpcExample_IfHandle);
 
        if (status != RPC_S_OK)
            continue;
 
        //Convert the binding to a string and display it to
        //the user/
 
        RpcBindingToStringBinding(RpcExample_IfHandle,&pszBind);
        _tprintf(TEXT("String Binding:%s\n"),pszBind);
 
        //Extract the service name, the host, in this case).
 
        ilen=_tcscspn((const TCHAR *)pszBind,TEXT(":"));
        _tcscpy(szServiceInstance,(const TCHAR *)(pszBind+ilen+1));
 
        RpcStringFree(&pszBind);
 
        //Make the RPC - Call the Server, then shut it down.
 
        RpcTryExcept {
            bResult = ServerProc((TCHAR *)TEXT("Text sent to server"));
            if (bResult) 
                _tprintf(TEXT("ServerProc: Server accepted call\n"));
            else
                _tprintf(TEXT("ServerProc: Server rejected call\n"));
 
            bResult = Shutdown();
            if (bResult) 
                _tprintf(TEXT("Shutdown: Server accepted call\n"));
            else
                _tprintf(TEXT("Shutdown: Server rejected call\n"));
            status  = RPC_S_NO_MORE_BINDINGS; //shut off the loop
        } 
        RpcExcept(1) {
            ulCode = RpcExceptionCode();
            _tprintf(TEXT("RPC exception 0x%lx = %ld\n"), ulCode, ulCode);
        }
        RpcEndExcept;
 
        //Free the imported binding.
 
        RpcBindingFree(&RpcExample_IfHandle);
    }
 
    //Discard the Import handle, we don't need it any more.
 
    status = RpcNsBindingImportDone(&hNs);