开发者

How to tell if the computer is part of a domain or not

Delphi Xe, Win7开发者_运维知识库

I need the following function:

Function isPcInDomain:bool;

The domain name does not interest me, msdn LsaQueryInformationPolicy too (Or give realisation on Delphi). I would like to have a function that does no need to query the network.

Also it must still work if the local name of the computer contains a .

Tried to define a domain name, but on the personal computer which not in the domain - as a domain name gives out a name of Local Working group :(


You can use NetGetJoinInformation:

program test;

{$APPTYPE CONSOLE}
{$MINENUMSIZE 4}

uses
  Windows, SysUtils;

const
  netapi = 'netapi32.dll';

type
  TNetSetupJoinStatus = (NetSetupUnknownStatus, NetSetupUnjoined, NetSetupWorkgroupName, NetSetupDomainName);

function NetApiBufferFree(Buffer: Pointer): DWORD; stdcall; external netapi;
function NetGetJoinInformation(lpServer: PWideChar; out lpNameBuffer: PWideChar;
  out BufferType: TNetSetupJoinStatus): Cardinal; stdcall; external netapi;

procedure NetApiCheck(RetValue: Cardinal);
begin
  if RetValue <> ERROR_SUCCESS then
    RaiseLastOSError(RetValue);
end;

function GetJoinInfo(out JoinStatus: TNetSetupJoinStatus): WideString;
var
  P: PWideChar;
begin
  NetApiCheck(NetGetJoinInformation(nil, P, JoinStatus));
  Result := P;
  NetApiBufferFree(P);
end;

procedure Main;
const
  JoinStatusStrings: array[TNetSetupJoinStatus] of string = ('Unknown', 'Unjoined', 'Workgroup', 'Domain');
var
  Info: TNetSetupJoinStatus;
  S: WideString;
begin
  S := GetJoinInfo(Info);
  Writeln(Format('%s %s', [JoinStatusStrings[Info], S]));
end;

begin
  try
    Main;
  except
    on E: Exception do
    begin
      ExitCode := 1;
      Writeln(Format('[%s] %s', [E.ClassName, E.Message]));
    end;
  end;
end.


uses
  LSAApi;

function isPcInDomain : Boolean;
var
  ComputerName : TLSAUnicodeStr;
  Attributes : TLsaObjectAttributes;
  PolicyHandle : LSA_HANDLE;
  Status : NTStatus;
  Buffer : Pointer;
  PolicyAccountDomainInfo : PPolicyAccountDomainInfo;
begin
  ComputerName := TLsaUnicodeStr.CreateFromStr('');
  try
    FillChar(Attributes, SizeOf(Attributes), 0);

    Status := LsaOpenPolicy(ComputerName.Value, Attributes, POLICY_VIEW_LOCAL_INFORMATION, PolicyHandle);
    if Status <> STATUS_SUCCESS then
      raise Exception.Create('LsaOpenPolicy Failed: '+SysErrorMessage(LsaNtStatusToWinError(Status)));

    try
      Status := LsaQueryInformationPolicy(PolicyHandle, PolicyPrimaryDomainInformation, Buffer);
      if Status <> STATUS_SUCCESS then
        raise Exception.Create('LsaQueryInformationPolicy Failed: '+SysErrorMessage(LsaNtStatusToWinError(Status)));

      try
        PolicyAccountDomainInfo := Buffer;
        Result := PolicyAccountDomainInfo.DomainSID <> nil
      finally
        LsaFreeMemory(Buffer)
      end;
    finally
      LsaClose(PolicyHandle)
    end;
  finally
    ComputerName.Free;
  end;
end;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜