登录 用户中心() [退出] 后台管理 注册
   
您的位置: 首页 >> 程序员学前班[不再更新,只读] >> 主题: [delphi/共享文件]NetSessionEnum 取得连接到 windows 共享目录的连接数     [回主站]     [分站链接]
标题
[delphi/共享文件]NetSessionEnum 取得连接到 windows 共享目录的连接数
clq
浏览(0) + 2009-11-23 12:29:46 发表 编辑

关键字:

[2022-04-19 13:16:18 最后更新]
[delphi/共享文件]NetSessionEnum 取得连接到 windows 共享目录的连接数


这个在操作系统中是在"计算机管理"->"共享文件夹"->"共享"中可以看到到的。

程序要用 NetSessionEnum 函数来取得,对于 delphi 一些相关的例子已经老了,是 win98 的.

--------------------------------------------------
function ListCount(const aServer:string):integer;
var
EntriesRead : DWord;
I : Integer;
ResumeHandle : DWord;
Rslt : LongWord;
SessionInfo,
P : PSessionInfo502;
TotalEntries : DWord;
TotalSoFar : LongWord;
CName : PWideChar;
aString : string;
intIPAdres : integer;
strIPAdres : string;
count:integer;
begin
ResumeHandle := 0;
TotalSoFar := 0;
count := 0;


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
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';

clq
2009-11-23 12:31:43 发表 编辑

http://www.experts-exchange.com/Programming/Languages/Pascal/Delphi/Q_22675157.html
--------------------------------------------------
这个网站的回复质量很高。


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


Expert Comment
sas13:
unit ActiveConnections;

interface

uses
Windows, SysUtils,
StdCtrls, ShlObj, ExtCtrls, ComCtrls, ShellApi, Grids, WinSock,
frmMain;


const
MAX_PREFERRED_LENGTH = DWord(-1);

type
PSessionInfo502 = ^TSessionInfo502;
TSessionInfo502 = packed record
sesi502_cname : PWideChar;
sesi502_username : PWideChar;
sesi502_num_opens : LongWord;
sesi502_time : LongWord;
sesi502_idle_time : LongWord;
sesi502_user_flags : LongWord;
sesi502_cltype_name : PWideChar;
sesi502_transport : PWideChar;
end;

procedure ListLoggedOnUsers(aStringGrid: TStringGrid; const aServer:
string);

function NetSessionEnum(ServerName,
UncClientName,
UserName: PWideChar;
Level: DWord;
var Buffer: Pointer;
PrefMaxLen: DWord;
var EntriesRead,
TotalEntries,
ResumeHandle: DWord): LongWord; stdcall;
external 'netapi32.dll';


implementation


procedure ListLoggedOnUsers(aStringGrid: TStringGrid; const aServer:
string);
var
EntriesRead : DWord;
I : Integer;
ResumeHandle : DWord;
Rslt : LongWord;
SessionInfo,
P : PSessionInfo502;
TotalEntries : DWord;
TotalSoFar : LongWord;
CName : PWideChar;
aString : string;
intIPAdres : integer;
strIPAdres : string;
begin
ResumeHandle := 0;
TotalSoFar := 0;
//StringGridUsers.RowCount := 2;
aStringGrid.RowCount := 2;
aStringGrid.Cells[0, 0] := 'User';
aStringGrid.Cells[1, 0] := 'Computer';
aStringGrid.Cells[2, 0] := 'ActiveTime';
aStringGrid.Cells[3, 0] := 'Connections';
aStringGrid.ColWidths[3] := 70;
aStringGrid.Cells[4, 0] := 'IP Adres';
aStringGrid.Cells[5, 0] := 'Client Type';
aStringGrid.ColWidths[5] := 140;
aStringGrid.Cells[0, 1] := 'Nobody';
aStringGrid.Cells[1, 1] := 'has';
aStringGrid.Cells[2, 1] := 'Logged';
aStringGrid.Cells[3, 1] := 'in';
aStringGrid.Cells[4, 1] := 'right';
aStringGrid.Cells[5, 1] := 'now...';

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)

05/07/07 01:47 AM, ID: 19422563Author Comment
bengore:
better solution:

"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


----------------------- PAS

unit Unit1;

interface

uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ComCtrls, StdCtrls;

type
TForm1 = class(TForm)
Button1: TButton;
ListView1: TListView;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;

var
Form1: TForm1;

implementation

{$R *.dfm}

const
MAX_PREFERRED_LENGTH = DWord(-1);

type
PSessionInfo1 = ^TSessionInfo1;
TSessionInfo1 = packed record
ComputerName: PWideChar;
UserName: PWideChar;
NumOpenConnections: LongWord;
ActiveTime: LongWord;
IdleTime: LongWord;
UserFlags: LongWord
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.

Computer101
EE Admin

clq
2009-11-23 12:34:22 发表 编辑

msdn 的.
--------------------------------------------------

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.

#ifndef UNICODE
#define UNICODE
#endif

#include
#include
#include
#include

int wmain(int argc, wchar_t *argv[])
{
LPSESSION_INFO_10 pBuf = NULL;
LPSESSION_INFO_10 pTmpBuf;
DWORD dwLevel = 10;
DWORD dwPrefMaxLen = -1;
DWORD dwEntriesRead = 0;
DWORD dwTotalEntries = 0;
DWORD dwResumeHandle = 0;
DWORD i;
DWORD dwTotalCount = 0;
LPTSTR pszServerName = NULL;
LPTSTR pszClientName = NULL;
LPTSTR pszUserName = NULL;
NET_API_STATUS nStatus;
//
// Check command line arguments.
//
if (argc > 4)
{
wprintf(L"Usage: %s [\\\\ServerName] [\\\\ClientName] [UserName]\n", argv[0]);
exit(1);
}

if (argc >= 2)
pszServerName = argv[1];

if (argc >= 3)
pszClientName = argv[2];

if (argc == 4)
pszUserName = argv[3];
//
// Call the NetSessionEnum function, specifying level 10.
//
do // begin do
{
nStatus = NetSessionEnum(pszServerName,
pszClientName,
pszUserName,
dwLevel,
(LPBYTE*)&pBuf,
dwPrefMaxLen,
&dwEntriesRead,
&dwTotalEntries,
&dwResumeHandle);
//
// If the call succeeds,
//
if ((nStatus == NERR_Success) || (nStatus == ERROR_MORE_DATA))
{
if ((pTmpBuf = pBuf) != NULL)
{
//
// Loop through the entries.
//
for (i = 0; (i < dwEntriesRead); i++)
{
assert(pTmpBuf != NULL);

if (pTmpBuf == NULL)
{
fprintf(stderr, "An access violation has occurred\n");
break;
}
//
// Print the retrieved data.
//
wprintf(L"\n\tClient: %s\n", pTmpBuf->sesi10_cname);
wprintf(L"\tUser: %s\n", pTmpBuf->sesi10_username);
printf("\tActive: %d\n", pTmpBuf->sesi10_time);
printf("\tIdle: %d\n", pTmpBuf->sesi10_idle_time);

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


总数:2 页次:1/1 首页 尾页  
总数:2 页次:1/1 首页 尾页  


所在合集/目录



发表评论:
文本/html模式切换 插入图片 文本/html模式切换


附件:



NEWBT官方QQ群1: 276678893
可求档连环画,漫画;询问文本处理大师等软件使用技巧;求档softhub软件下载及使用技巧.
但不可"开车",严禁国家敏感话题,不可求档涉及版权的文档软件.
验证问题说明申请入群原因即可.

Copyright © 2005-2020 clq, All Rights Reserved
版权所有
桂ICP备15002303号-1