这是我使用 winsocks2 和 unicode 支持解析 XE3-XE7 上的 IP 地址的自包含示例。
它不是高性能的,因为套接字支持在每次调用时都会被初始化和取消初始化,但重构是微不足道的。
另外,请注意,它不是为了便于维护而特意优化的。
uses
Winapi.Winsock2;
type
PAddrInfo = ^TAddrInfo;
TAddrInfo = packed record
ai_flags: integer;
ai_family: integer;
ai_socktype: integer;
ai_protocol: integer;
ai_addrlen: NativeInt;
ai_canonname: PCHAR;
ai_addr: PSOCKADDR;
ai_next: PAddrInfo;
end;
function GetAddrInfo(const nodeName: PCHAR; const serviceName : PChar; const hints: PAddrInfo; var result: PAddrInfo): integer; stdcall; external 'ws2_32.dll' name 'GetAddrInfoW';
procedure FreeAddrInfo(const addrInfo: PAddrInfo); stdcall; external 'ws2_32.dll' name 'FreeAddrInfoW';
function ResolveIpAddress(const hostName: string; const ipv6: boolean): string;
const
BUFFER_SIZE = 32768;
var
data: TWSAData;
error: integer;
requestError: integer;
r: PAddrInfo;
s: string;
hints: TAddrInfo;
buffer: TArray<byte>;
length: DWORD;
begin
error:= WSAStartup(MAKEWORD(2, 2), data);
try
if (error = 0) then
begin
r:= nil;
try
ZeroMemory(@hints, sizeof(TAddrInfo));
if (ipv6) then
hints.ai_family:= AF_INET6
else
hints.ai_family:= AF_INET;
requestError:= GetAddrInfo(PCHAR(hostName), nil, @hints, r);
if (requestError = 0) then
begin
length:= BUFFER_SIZE;
SetLength(buffer, BUFFER_SIZE);
if (WSAAddressToString(r.ai_addr^, r.ai_addrlen, nil, @buffer[0], length) = 0) then
begin
setLength(buffer, length * 2);
s:= TUnicodeEncoding.Unicode.GetString(@buffer[0]);
exit(s);
end
else
exit('0.0.0.0');
end
else
exit('0.0.0.0');
finally
FreeAddrInfo(r);
end;
end
finally
if (error = 0) then
WSACleanup();
end;
end;