repeat Rslt := NetSessionEnum(CName, NIL, NIL, 502, Pointer(SessionInfo), MAX_PREFERRED_LENGTH, EntriesRead, TotalEntries, ResumeHandle); if Rslt <> 0 then begin raise Exception.CreateFmt('Network API error %d', [Rslt]); end;
P := SessionInfo; for I := 0 to EntriesRead - 1 do begin if WideCharToString(P.sesi502_username) <> '' then begin //aStringGrid.RowCount := aStringGrid.RowCount + 1; count := count+1; end; Inc(LongWord(P), SizeOf(TSessionInfo502)) end;
Inc(TotalSoFar, EntriesRead);
until TotalSoFar >= TotalEntries;
Rslt := NetApiBufferFree(SessionInfo);
if Rslt <> 0 then begin raise Exception.CreateFmt('Network API error %d', [Rslt]); end;
result := count;
end; -------------------------------------------------- function NetApiBufferFree(Buffer: Pointer): LongWord; stdcall; external 'netapi32.dll';
function NetSessionEnum(ServerName, UncClientName, UserName: PWideChar; Level: LongWord; var Buffer: Pointer; PrefMaxLen: LongWord; var EntriesRead, TotalEntries, ResumeHandle: LongWord): LongWord; stdcall; external 'netapi32.dll';
NetSessionEnum sample Asked by bengore in Delphi Programming I need a short NetSessionEnum sample to enumerate all username which are connected with a machine ABC. My Problem: I have established a connection to machine ABC with another username then the current logged-in user. How to get this "another" username? Thank you
aString := aServer;//EditServer.text; CName := StringToOleStr(aString); repeat Rslt := NetSessionEnum(CName, NIL, NIL, 502, Pointer(SessionInfo), MAX_PREFERRED_LENGTH, EntriesRead, TotalEntries, ResumeHandle); if Rslt <> 0 then raise Exception.CreateFmt('Network API error %d', [Rslt]); P := SessionInfo; for I := 0 to EntriesRead - 1 do begin if WideCharToString(P.sesi502_username) <> '' then begin aStringGrid.Cells[0, aStringGrid.RowCount - 1] := WideCharToString(P.sesi502_username); aStringGrid.Cells[1, aStringGrid.RowCount - 1] := WideCharToString(P.sesi502_cname); aStringGrid.Cells[2, aStringGrid.RowCount - 1] := formMain.SecondsToTimeString(P.sesi502_time); aStringGrid.Cells[3, aStringGrid.RowCount - 1] := IntToStr(P.sesi502_num_opens); if formMain.GetIPByName(P.sesi502_cname, intIPAdres, strIPAdres) then aStringGrid.Cells[4, aStringGrid.RowCount - 1] := strIPAdres; aStringGrid.Cells[5, aStringGrid.RowCount - 1] := WideCharToString(P.sesi502_cltype_name); aStringGrid.RowCount := aStringGrid.RowCount + 1; end; Inc(LongWord(P), SizeOf(TSessionInfo502)) end; Inc(TotalSoFar, EntriesRead); until TotalSoFar >= TotalEntries; aStringGrid.RowCount := aStringGrid.RowCount - 1; Rslt := NetApiBufferFree(SessionInfo); if Rslt <> 0 then raise Exception.CreateFmt('Network API error %d', [Rslt]) end;
end.
05/07/07 12:02 AM, ID: 19422232Author Comment bengore: Thank you for the source! I have one question: CName := StringToOleStr(aString); How the free or dispose CName? I think, without Free(CName) there would be a memory leak!?
05/07/07 12:15 AM, ID: 19422285Author Comment bengore: I found another memory leak. You have to add if SessionInfo<>nil NetApiBufferFree(SessionInfo); befor the line until TotalSoFar >= TotalEntries;
So this part of souce code should look like: .... Inc(TotalSoFar, EntriesRead); if SessionInfo<>nil then NetApiBufferFree(SessionInfo); until TotalSoFar >= TotalEntries; if SessionInfo<>nil then NetApiBufferFree(SessionInfo); ...
(See http://msdn.microsoft.com/library/en-us/stgmgmt/fs/netsessionenum.asp)
"inc(p);" works also instead of "Inc(LongWord(P), SizeOf(TSessionInfo502))" .... Inc(TotalSoFar, EntriesRead); if SessionInfo<>nil then begin NetApiBufferFree(SessionInfo); SessionInfo:=nil; end; until TotalSoFar >= TotalEntries; if SessionInfo<>nil then NetApiBufferFree(SessionInfo); ...
06/07/07 02:12 AM, ID: 19430375Author Comment bengore: sas13, thank you for your posting. I don't know if your solution works. But I think it is better to translate the Microsoft sample (http://msdn.microsoft.com/library/en-us/stgmgmt/fs/netsessionenum.asp). I did it and it works fine without memory leaks. How do I award the points?
Ben
03/08/07 01:22 AM, ID: 19623289Accepted Solution sas13: this example worked without any memleaks:
--------------------- DFM
object Form1: TForm1 Left = 312 Top = 285 Width = 373 Height = 315 Caption = 'Form1' Color = clBtnFace Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -11 Font.Name = 'MS Sans Serif' Font.Style = [] OldCreateOrder = False PixelsPerInch = 96 TextHeight = 13 object Button1: TButton Left = 24 Top = 16 Width = 75 Height = 25 Caption = 'Button1' TabOrder = 0 OnClick = Button1Click end object ListView1: TListView Left = 16 Top = 56 Width = 329 Height = 193 Columns = < item Caption = 'User' Width = 100 end item Caption = 'Computer' Width = 200 end> ReadOnly = True TabOrder = 1 ViewStyle = vsReport end end
function NetApiBufferFree(Buffer: Pointer): LongWord; stdcall; external 'netapi32.dll';
function NetSessionEnum(ServerName, UncClientName, UserName: PWideChar; Level: LongWord; var Buffer: Pointer; PrefMaxLen: LongWord; var EntriesRead, TotalEntries, ResumeHandle: LongWord): LongWord; stdcall; external 'netapi32.dll';
procedure ListLoggedOnUsers(AListView: TListView); var EntriesRead: LongWord; I: Integer; ResumeHandle: LongWord; Rslt: LongWord; SessionInfo, P: PSessionInfo1; TotalEntries: LongWord; TotalSoFar: LongWord; begin ResumeHandle := 0; TotalSoFar := 0; AListView.Items.BeginUpdate; try AListView.Clear; repeat Rslt := NetSessionEnum(nil, nil, nil, 1, Pointer(SessionInfo), MAX_PREFERRED_LENGTH, EntriesRead, TotalEntries, ResumeHandle); if Rslt <> 0 then raise Exception.CreateFmt('Network API error %d', [Rslt]); P := SessionInfo; for I := 0 to EntriesRead - 1 do begin with AListView.Items.Add do begin Caption := WideCharToString(P.UserName); SubItems.Add(WideCharToString(P.ComputerName)); end; Inc(LongWord(P), SizeOf(TSessionInfo1)) end; Inc(TotalSoFar, EntriesRead); Rslt := NetApiBufferFree(SessionInfo); if Rslt <> 0 then raise Exception.CreateFmt('Network API error %d', [Rslt]) until TotalSoFar >= TotalEntries; finally AListView.Items.EndUpdate end; end;
procedure TForm1.Button1Click(Sender: TObject); begin ListLoggedOnUsers(ListView1); end;
end. Accepted Solution
21/03/08 12:39 PM, ID: 21182534Administrative Comment ciuly: No comment has been added to this question in more than 21 days, so it is now classified as abandoned.
I will leave the following recommendation for this question in the Cleanup topic area: Accept: sas13 {http:#19623289}
Any objections should be posted here in the next 4 days. After that time, the question will be closed.
ciuly EE Cleanup Volunteer
Computer101 03.25.2008 at 03:55PM PDT, ID: 21207207 Forced accept.
Platform SDK: Network Management NetSessionEnum The NetSessionEnum function provides information about sessions established on a server.
Security Requirements Only members of the Administrators or Account Operators local group can successfully execute the NetSessionEnum function at level 1 or level 2. No special group membership is required for level 0 or level 10 calls.
Windows NT/2000/XP: The parameter order is as follows.
NET_API_STATUS NetSessionEnum( LPWSTR servername, LPWSTR UncClientName, LPWSTR username, DWORD level, LPBYTE *bufptr, DWORD prefmaxlen, LPDWORD entriesread, LPDWORD totalentries, LPDWORD resume_handle ); Windows 95/98/Me: The calling application must use the cbBuffer parameter to specify the size, in bytes, of the information buffer pointed to by the pbBuffer parameter. (The cbBuffer parameter replaces the Windows NT/Windows 2000/Windows XP prefmaxlen parameter.) Neither a user name parameter nor a resume handle parameter is available on this platform. Therefore, the parameter list is as follows.
extern API_FUNCTION NetSessionEnum( const char FAR * pszServer, short sLevel, char FAR * pbBuffer, unsigned short cbBuffer, unsigned short FAR * pcEntriesRead, unsigned short FAR * pcTotalAvail ); Parameters servername [in] Pointer to a Unicode (Windows NT/2000/XP) or ANSI (Windows 95/98/Me) string specifying the name of the remote server on which the function is to execute. The string must begin with \\. If this parameter is NULL, the local computer is used. UncClientName [in] Pointer to a Unicode string specifying the name of the computer session for which information is to be returned. If this parameter is NULL, NetSessionEnum returns information for all computer sessions on the server. username [in] Pointer to a Unicode string specifying the name of the user for which information is to be returned. If this parameter is NULL, NetSessionEnum returns information for all users. level [in] Specifies the information level of the data. This parameter can be one of the following values. Windows NT/2000/XP: The following levels are valid. Value Meaning 0 Return the name of the computer that established the session. The bufptr parameter points to an array of SESSION_INFO_0 structures. 1 Return the name of the computer, name of the user, and open files, pipes, and devices on the computer. The bufptr parameter points to an array of SESSION_INFO_1 structures. 2 In addition to the information indicated for level 1, return the type of client and how the user established the session. The bufptr parameter points to an array of SESSION_INFO_2 structures. 10 Return the name of the computer, name of the user, and active and idle times for the session. The bufptr parameter points to an array of SESSION_INFO_10 structures. 502 Return the name of the computer; name of the user; open files, pipes, and devices on the computer; and the name of the transport the client is using. The bufptr parameter points to an array of SESSION_INFO_502 structures.
Windows 95/98/Me: The following level is valid. Value Meaning 50 Return the name of the computer, name of the user, open files on the computer, and the name of the transport protocol the client is using. The pbBuffer parameter points to an array of session_info_50 structures.
bufptr [out] Pointer to the buffer that receives the data. The format of this data depends on the value of the level parameter. Windows NT/2000/XP: This buffer is allocated by the system and must be freed using the NetApiBufferFree function. Note that you must free the buffer even if the function fails with ERROR_MORE_DATA.
Windows 95/98/Me: The caller must allocate and deallocate this buffer.
prefmaxlen [in] Specifies the preferred maximum length of returned data, in bytes. If you specify MAX_PREFERRED_LENGTH, the function allocates the amount of memory required for the data. If you specify another value in this parameter, it can restrict the number of bytes that the function returns. If the buffer size is insufficient to hold all entries, the function returns ERROR_MORE_DATA. For more information, see Network Management Function Buffers and Network Management Function Buffer Lengths. entriesread [out] Pointer to a value that receives the count of elements actually enumerated. totalentries [out] Pointer to a value that receives the total number of entries that could have been enumerated from the current resume position. resume_handle [in/out] Pointer to a DWORD value that contains a resume handle which is used to continue an existing session search. The handle should be zero on the first call and left unchanged for subsequent calls. If resume_handle is NULL, no resume handle is stored. Return Values If the function succeeds, the return value is NERR_Success.
If the function fails, the return value can be one of the following error codes.
Value Meaning ERROR_ACCESS_DENIED The user does not have access to the requested information. ERROR_INVALID_LEVEL The value specified for the level parameter is invalid. ERROR_INVALID_PARAMETER The specified parameter is invalid. ERROR_MORE_DATA More entries are available. Specify a large enough buffer to receive all entries. ERROR_NOT_ENOUGH_MEMORY Insufficient memory is available. NERR_ClientNameNotFound A session does not exist with the computer name. NERR_InvalidComputer The computer name is invalid. NERR_UserNotFound The user name could not be found.
Remarks Windows 95/98/Me: See the NetSessionEnum Sample (Windows 95/98) topic to view a code sample that demonstrates how to use the NetSessionEnum function.
Windows NT/2000/XP: The following code sample demonstrates how to retrieve information about current sessions using a call to the NetSessionEnum function. The sample calls NetSessionEnum, specifying information level 10 (SESSION_INFO_10). The sample loops through the entries and prints the retrieved information. Finally, the code prints the total number of sessions enumerated and frees the memory allocated for the information buffer.
pTmpBuf++; dwTotalCount++; } } } // // Otherwise, indicate a system error. // else fprintf(stderr, "A system error has occurred: %d\n", nStatus); // // Free the allocated memory. // if (pBuf != NULL) { NetApiBufferFree(pBuf); pBuf = NULL; } } // // Continue to call NetSessionEnum while // there are more entries. // while (nStatus == ERROR_MORE_DATA); // end do
// Check again for an allocated buffer. // if (pBuf != NULL) NetApiBufferFree(pBuf); // // Print the final count of sessions enumerated. // fprintf(stderr, "\nTotal of %d entries enumerated\n", dwTotalCount);
return 0; } If you are programming for Active Directory, you may be able to call certain Active Directory Service Interface (ADSI) methods to achieve the same functionality you can achieve by calling the network management session functions. For more information, see IADsSession and IADsFileServiceOperations.
Requirements Windows NT/2000/XP: Included in Windows NT 3.1 and later. Windows 95/98/Me: Included in Windows 95 and later. Header: Declared in Lmshare.h (Windows NT/2000/XP) or Svrapi.h (Windows 95/98/Me); include Lm.h (Windows NT/2000/XP). Library: Use Netapi32.lib (Windows NT/2000/XP) or Svrapi.lib (Windows 95/98/Me).
See Also Network Management Overview, Network Management Functions, Session Functions, NetSessionGetInfo, SESSION_INFO_0, SESSION_INFO_1, SESSION_INFO_2, SESSION_INFO_10, SESSION_INFO_502, session_info_50
Platform SDK Release: August 2001 What did you think of this topic? Let us know. Order a Platform SDK CD Online (U.S/Canada) (International)
Requirements Windows NT/2000/XP: Included in Windows NT 3.1 and later. Windows 95/98/Me: Included in Windows 95 and later. Header: Declared in Lmshare.h (Windows NT/2000/XP) or Svrapi.h (Windows 95/98/Me); include Lm.h (Windows NT/2000/XP). Library: Use Netapi32.lib (Windows NT/2000/XP) or Svrapi.lib (Windows 95/98/Me). See Also Network Management Overview, Network Management Functions, Session Functions, NetSessionGetInfo, SESSION_INFO_0, SESSION_INFO_1, SESSION_INFO_2, SESSION_INFO_10, SESSION_INFO_502, session_info_50