gpt4 book ai didi

delphi - 内存泄漏GETIPFROMHOST

转载 作者:行者123 更新时间:2023-12-03 14:52:30 26 4
gpt4 key购买 nike

我这里有这段代码,用于从主机名检索 IP 地址:

program Project1;

{$APPTYPE CONSOLE}

uses
SysUtils,
winsock;

function GetIPFromHost(const HostName: string): string;
type
TaPInAddr = array[0..10] of PInAddr;
PaPInAddr = ^TaPInAddr;
var
phe: PHostEnt;
pptr: PaPInAddr;
i: Integer;
begin
Result := '';
phe := GetHostByName(PChar(HostName));
if phe = nil then Exit;
pPtr := PaPInAddr(phe^.h_addr_list);
i := 0;
while pPtr^[i] <> nil do
begin
Result := inet_ntoa(pptr^[i]^);
Inc(i);
end;
end;

var
wsaData: TWSAData;

begin

if (WSAStartup($0202, wsaData) <> 0) then begin
Exit;
end;

while true do begin
sleep (1000);
GetIPFromHost ('localhost');
end;

它工作正常并给了我 IP 地址。不幸的是,我多次需要这个函数来比较 DNS 和 IP 地址。

由于某种原因,我遇到了严重的内存泄漏,并且我的程序的内存增加得非常快。这是为什么?我怎样才能释放内存?

提前致谢。

最佳答案

以下是 GetIPAddressJclSysInfo 中的实现方式:

function GetIPAddress(const HostName: string): string;
var
R: Integer;
WSAData: TWSAData;
HostEnt: PHostEnt;
Host: string;
SockAddr: TSockAddrIn;
begin
Result := '';
R := WSAStartup(MakeWord(1, 1), WSAData);
if R = 0 then
try
Host := HostName;
if Host = '' then
begin
SetLength(Host, MAX_PATH);
GetHostName(PChar(Host), MAX_PATH);
end;
HostEnt := GetHostByName(PChar(Host));
if HostEnt <> nil then
begin
SockAddr.sin_addr.S_addr := Longint(PLongint(HostEnt^.h_addr_list^)^);
Result := inet_ntoa(SockAddr.sin_addr);
end;
finally
WSACleanup;
end;
end;

请注意,您缺少 WSACleanup .

<小时/>

An application or DLL is required to perform a successful WSAStartup call before it can use Windows Sockets services. When it has completed the use of Windows Sockets, the application or DLL must call WSACleanup to deregister itself from a Windows Sockets implementation and allow the implementation to free any resources allocated on behalf of the application or DLL.

关于delphi - 内存泄漏GETIPFROMHOST,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9050706/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com