NaN
NaN

Reputation: 9104

How to get a list with all computers from the local network?

This code I've got a long time ago was supposed to return a string list with each computer connected to my Windows workgroup but when I tested I get only my own computer, but I have three computers connected with the same workgroup name and appearing in my Windows Explorer Network List.

What could be wrong? Is there another way to do it?

function FindAllComputers(Workgroup: string; WithIP: Boolean): TStringList;
var
  EnumHandle : THandle;
  WorkgroupRS : TNetResource;
  Buf : Array[1..500] of TNetResource;
  BufSize : cardinal;
  Entries : cardinal;
  Res : Integer;
  Computers : Tstringlist;
  Limit, I: Integer;
begin
  Limit := 0;
  Workgroup := Workgroup + #0;
  FillChar(WorkgroupRS, SizeOf(WorkgroupRS) , 0);
  With WorkgroupRS do
  begin
    dwScope := 2;
    dwType := 3;
    dwDisplayType := 1;
    dwUsage := 2;
    lpRemoteName := @Workgroup[1];
  end;
  WNetOpenEnum(RESOURCE_GLOBALNET, RESOURCETYPE_ANY, 0, 
    @WorkgroupRS, EnumHandle);
  Computers := TStringList.Create;
  repeat
    Entries := 1;
    BufSize := SizeOf(Buf);
    Res := WNetEnumResource(EnumHandle, Entries, @Buf, BufSize);
    if (Res = NO_ERROR) and (Entries = 1) then
    begin
      Computers.Add(StrPas(Buf[1].lpRemoteName));
    end;
    Inc(Limit);
  until (Entries > 0) or (Res <> NO_ERROR) or (Limit > 100);
  WNetCloseEnum( EnumHandle );
  if WithIP then
  begin
    for I := 0 to Computers.Count-1 do
      Computers[I] := Computers[I] + '=' + GetIP(Computers[I]);
  end;
  Result := Computers;
end;

Upvotes: 0

Views: 3384

Answers (1)

Sertac Akyuz
Sertac Akyuz

Reputation: 54822

See the documentation for WNetEnumResource, 'lpcCount' ('Entries' parameter in your code') on return receives the number of items enumerated. You're terminating the enumeration if it is greater than 0, but this is expected. You're requesting one item to be enumerated and the function does that and sets it to 1. Just remove that condition from loop termination:

..
until (Res <> NO_ERROR) or (Limit > 100);
..

You may also want to review the code, f.i. you don't need StrPas.

Upvotes: 5

Related Questions