获取 Delphi 中所有连接的 IP 地址
Get IP address for all connections in Delphi
以下代码 returns 机器的第一个 TCP/IP 连接的 IP 地址。
uses WinSock;
// ...
function GetLocalIP() : String;
var
addr: TSockAddrIn;
phe: PHostEnt;
szHostName: array[0..128] of Char;
socketData: TWSADATA;
begin
Result := '127.0.0.1';
// Initialize the socket API
if (WSAStartup(1, socketData) = 0) then
begin
// Get local machine name
if (GetHostName(szHostName, 128) = SOCKET_ERROR) then
Exit;
// Use name to find IP address
phe := GetHostByName(szHostName);
if (phe = nil) then
Exit;
addr.sin_addr.S_addr := Longint(PLongint(phe^.h_addr_list^)^);
// Convert IP address to PChar format
Result := inet_ntoa(addr.sin_addr);
end;
end;
// ...
Label1.Caption := GetLocalIP();
我需要进行哪些修改才能获取所有 TCP/IP 网络连接(有多个)的 IP 地址?
我确实在这篇相关文章中偶然发现了这一点:
Get information about the installed network adapters
这似乎使用了一种不同的技术,使用 Windows API "GetAdaptersInfo"...这是要走的路吗?
如果要枚举本机当前可用的IP地址,使用GetAdaptersInfo()
or GetAdaptersAddresses()
。
如果要枚举本地计算机当前活动的 TCP/IP 套接字连接,请使用 GetTcpTable()
or GetTcpTable2()
for IPv4 connections, and GetTcp6Table()
or GetTcp6Table2()
获取 IPv6 连接。
以下代码 returns 机器的第一个 TCP/IP 连接的 IP 地址。
uses WinSock;
// ...
function GetLocalIP() : String;
var
addr: TSockAddrIn;
phe: PHostEnt;
szHostName: array[0..128] of Char;
socketData: TWSADATA;
begin
Result := '127.0.0.1';
// Initialize the socket API
if (WSAStartup(1, socketData) = 0) then
begin
// Get local machine name
if (GetHostName(szHostName, 128) = SOCKET_ERROR) then
Exit;
// Use name to find IP address
phe := GetHostByName(szHostName);
if (phe = nil) then
Exit;
addr.sin_addr.S_addr := Longint(PLongint(phe^.h_addr_list^)^);
// Convert IP address to PChar format
Result := inet_ntoa(addr.sin_addr);
end;
end;
// ...
Label1.Caption := GetLocalIP();
我需要进行哪些修改才能获取所有 TCP/IP 网络连接(有多个)的 IP 地址?
我确实在这篇相关文章中偶然发现了这一点: Get information about the installed network adapters 这似乎使用了一种不同的技术,使用 Windows API "GetAdaptersInfo"...这是要走的路吗?
如果要枚举本机当前可用的IP地址,使用GetAdaptersInfo()
or GetAdaptersAddresses()
。
如果要枚举本地计算机当前活动的 TCP/IP 套接字连接,请使用 GetTcpTable()
or GetTcpTable2()
for IPv4 connections, and GetTcp6Table()
or GetTcp6Table2()
获取 IPv6 连接。