delphi 获取本地网络连接


本文整理自网络,侵删。

 
program Project1;

{$APPTYPE CONSOLE}

{$R *.res}

uses
  System.SysUtils, WinSock,
  Windows;


const
   ANY_SIZE = 1;
   iphlpapi = 'iphlpapi.dll';
   TCP_TABLE_OWNER_PID_ALL = 5;

   MIB_TCP_STATE:
   array[1..12] of string = ('CLOSED', 'LISTEN', 'SYN-SENT ','SYN-RECEIVED', 'ESTABLISHED', 'FIN-WAIT-1',
                             'FIN-WAIT-2', 'CLOSE-WAIT', 'CLOSING','LAST-ACK', 'TIME-WAIT', 'delete TCB');

type
  TCP_TABLE_CLASS = Integer;

  PMibTcpRowOwnerPid = ^TMibTcpRowOwnerPid;
  TMibTcpRowOwnerPid  = packed record
    dwState     : DWORD;
    dwLocalAddr : DWORD;
    dwLocalPort : DWORD;
    dwRemoteAddr: DWORD;
    dwRemotePort: DWORD;
    dwOwningPid : DWORD;
    end;

  PMIB_TCPTABLE_OWNER_PID  = ^MIB_TCPTABLE_OWNER_PID;
  MIB_TCPTABLE_OWNER_PID = packed record
   dwNumEntries: DWORD;
   table: Array [0..ANY_SIZE - 1] of TMibTcpRowOwnerPid;
  end;

var
   GetExtendedTcpTable:function  (pTcpTable: Pointer; dwSize: PDWORD; bOrder: BOOL; lAf: ULONG; TableClass: TCP_TABLE_CLASS; Reserved: ULONG): DWord; stdcall;

procedure ShowCurrentTCPConnections;
var
   Error      : DWORD;
   TableSize  : DWORD;
   i          : integer;
   IpAddress  : in_addr;
   RemoteIp   : string;
   LocalIp    : string;
   pTcpTable  : PMIB_TCPTABLE_OWNER_PID;
begin
  TableSize := 0;
  //Get the size o the tcp table
  Error := GetExtendedTcpTable(nil, @TableSize, False, AF_INET, TCP_TABLE_OWNER_PID_ALL, 0);
  if Error <> ERROR_INSUFFICIENT_BUFFER then exit;

  //alocate the buffer
  GetMem(pTcpTable, TableSize);
  try
   Writeln(Format('%-16s %-6s %-16s %-6s %s',['Local IP','Port','Remote IP','Port','Status']));
   //get the tcp table data
   if GetExtendedTcpTable(pTcpTable, @TableSize, TRUE, AF_INET, TCP_TABLE_OWNER_PID_ALL, 0) = NO_ERROR then
      for i := 0 to pTcpTable.dwNumEntries - 1 do
      begin
         IpAddress.s_addr := pTcpTable.Table[i].dwRemoteAddr;
         RemoteIp         := string(inet_ntoa(IpAddress));
         IpAddress.s_addr := pTcpTable.Table[i].dwLocalAddr;
         LocalIp          := string(inet_ntoa(IpAddress));
         Writeln(Format('%-16s %-6d %-16s %-6d %s',[LocalIp,pTcpTable.Table[i].dwLocalPort,RemoteIp,pTcpTable.Table[i].dwRemotePort,MIB_TCP_STATE[pTcpTable.Table[i].dwState]]));
      end;
  finally
     FreeMem(pTcpTable);
  end;
end;

相关阅读 >>

Delphi 图像分割

Delphi禁止用户切换任务

Delphi inputbox 用法

如何用Delphi实现windows xp中“本地连接”的启用和禁用

Delphi 判断网站文件是否存在

Delphi thttprio 控件调用webservice超时问题

Delphi webbrowser1 execwb 复制 新建 打开

Delphi 取得固定长度的随机字符串

Delphi用twebbrowser组件在Delphi中post数据和取得网页源文件

Delphi和金山词霸制作批量单词翻译

更多相关阅读请进入《Delphi》频道 >>



打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...