2 Copyright (C) 2010-2018 MegaBrutal
4 This unit is free software: you can redistribute it and/or modify
5 it under the terms of the GNU Lesser General Public License as published by
6 the Free Software Foundation, either version 3 of the License, or
7 (at your option) any later version.
9 This unit is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU Lesser General Public License for more details.
14 You should have received a copy of the GNU Lesser General Public License
15 along with this program. If not, see <http://www.gnu.org/licenses/>.
24 uses WinSock
, Sockets
, ctypes
;
28 PAddrInfo
= ^TAddrInfo
;
46 function getaddrinfo(NodeName
, ServiceName
: PChar
; Hints
: PAddrInfo
; var AddrInfo
: PAddrInfo
): cint
; stdcall;
47 external 'ws2_32.dll' name
'getaddrinfo';
49 procedure freeaddrinfo(AddrInfo
: PAddrInfo
); stdcall;
50 external 'ws2_32.dll' name
'freeaddrinfo';
52 function getnameinfo(SockAddr
: PSockAddr
; SockAddrLength
: cuint32
; NodeBuffer
: PChar
; NodeBufferSize
: cuint32
;
53 ServiceBuffer
: PChar
; ServiceBufferSize
: cuint32
; Flags
: cint
): cint
; stdcall;
54 external 'ws2_32.dll' name
'getnameinfo';
56 function ResolveHost(HostName
: ansistring
; Family
: cint
): TGAIResult
;
57 procedure FreeHost(var GAIResult
: TGAIResult
);
58 function ResolveIP(AddrInfo
: PAddrInfo
): ansistring
;
59 function IPToStr(SockAddr
: PSockAddr
): ansistring
;
65 function ResolveHost(HostName
: ansistring
; Family
: cint
): TGAIResult
;
68 FillByte(hint
, SizeOf(hint
), 0);
71 ai_socktype
:= SOCK_STREAM
;
72 ai_protocol
:= IPPROTO_TCP
;
74 ResolveHost
.GAIError
:= getaddrinfo(PChar(HostName
), nil, @hint
, ResolveHost
.AddrInfo
);
77 procedure FreeHost(var GAIResult
: TGAIResult
);
79 if GAIResult
.AddrInfo
<> nil then begin
80 freeaddrinfo(GAIResult
.AddrInfo
);
81 GAIResult
.AddrInfo
:= nil;
85 function ResolveIP(AddrInfo
: PAddrInfo
): ansistring
;
88 NodeBuffer
: array[0..255] of char;
91 r
:= getnameinfo(AddrInfo
^.ai_addr
, AddrInfo
^.ai_addrlen
, @NodeBuffer
, SizeOf(NodeBuffer
), nil, 0, 0);
92 if r
= 0 then ResolveIP
:= PChar(@NodeBuffer
)
93 else ResolveIP
:= IPToStr(AddrInfo
^.ai_addr
);
96 function IPToStr(SockAddr
: PSockAddr
): ansistring
;
98 if SockAddr
^.sa_family
= AF_INET
then
99 IPToStr
:= NetAddrToStr(SockAddr
^.sin_addr
)
100 else if SockAddr
^.sa_family
= AF_INET6
then
101 IPToStr
:= NetAddrToStr6(PSockAddr6(SockAddr
)^.sin6_addr
)