Title: Enumerating Network Connections
Question: How to detecting current network connections?
Answer:
From the MS-DOS prompt, you can enumerate the network connections (drives) by using the following command:
net use
Programmatically, you would call WNetOpenEnum() to start the enumeration of connected resources and WNetEnumResources() to continue the enumeration.
The following sample code enumerates the network connections:
Sample Code
-----------
procedure TForm1.Button1Click(Sender: TObject);
var
i, dwResult: DWORD ;
hEnum: THANDLE ;
lpnrDrv,
lpnrDrvLoc : PNETRESOURCE ;
s: string;
const
cbBuffer:DWORD = 16384;
cEntries: DWORD = $FFFFFFFF;
begin
dwResult := WNetOpenEnum( RESOURCE_CONNECTED,
RESOURCETYPE_ANY,
0,
nil,
hEnum );
if (dwResult NO_ERROR) then begin
ShowMessage('Cannot enumerate network drives.' );
Exit;
end;
s := '';
repeat
lpnrDrv := PNETRESOURCE (GlobalAlloc( GPTR, cbBuffer ));
dwResult := WNetEnumResource( hEnum, cEntries, lpnrDrv, cbBuffer);
if (dwResult = NO_ERROR) then begin
s := 'Network drives:'#13#10;
lpnrDrvLoc := lpnrDrv;
for i := 0 to cEntries - 1 do begin
if lpnrDrvLoc^.lpLocalName nil then
s := s + lpnrDrvLoc^.lpLocalName + #9 + lpnrDrvLoc^.lpRemoteName + #13#10;
Inc(lpnrDrvLoc);
end;
end
else
if dwResult ERROR_NO_MORE_ITEMS then begin
s := s + 'Cannot complete network drive enumeration';
GlobalFree( HGLOBAL(lpnrDrv));
break;
end;
GlobalFree( HGLOBAL(lpnrDrv) );
until (dwResult = ERROR_NO_MORE_ITEMS );
WNetCloseEnum(hEnum);
if s = '' then s := 'No network connections.';
ShowMessage(s);
end;