gethostbyaddr:依 IPv4 位址 (in_addr) 反向解析主機名稱 (PTR 記錄)。需搭配 inet_addr 將字串 IP 轉為 in_addr。
uses Winsock, SysUtils;
function GetHostNameByIP(const IP: string): string;
var
WSAData: TWSAData;
Addr: TInAddr;
HostEnt: PHostEnt;
begin
Result := '';
if WSAStartup($0202, WSAData) <> 0 then Exit;
try
Addr.S_addr := inet_addr(PAnsiChar(AnsiString(IP)));
if Addr.S_addr = INADDR_NONE then Exit; // 格式錯誤
HostEnt := gethostbyaddr(@Addr, SizeOf(Addr), PF_INET);
if HostEnt <> nil then
Result := StrPas(HostEnt.h_name);
finally
WSACleanup;
end;
end;
procedure TForm1.btnResolveClick(Sender: TObject);
begin
edtHostName.Text := GetHostNameByIP(edtIP.Text);
if edtHostName.Text = '' then
ShowMessage('無法解析,可能無 PTR 記錄或 IP 格式錯誤');
end;
gethostbyaddr 僅支援 IPv4;IPv6 需使用 GetNameInfoW (Win32 API) 或 TIdStack.ResolveHost (Indy)。uses IdStack;
function GetHostNameByIP_Indy(const IP: string): string;
begin
Result := GStack.ResolveHost(IP); // 內部處理 IPv4/IPv6、非阻塞可選
end;