How to get the IP address from a DNS for a host name?
delphi, delphi-xe3, dns, ip
Solution
The big difference between these two versions of Delphi is that the modern Delphi natively uses wide UTF-16 encoded strings, and the older version has ANSI encoded strings.
Many API functions have both wide and ANSI versions. But the functions you are calling in Winsock are steadfastly 8 bit only.
You can make your code work as before by explicitly using 8 bit text encoding.
function GetIP(const HostName: string): string;
var
WSAData: TWSAData;
R: PHostEnt;
A: TInAddr;
begin
Result := IPNULL; // '0.0.0.0'
WSAStartup($101, WSAData);
R := Winsock.GetHostByName(PAnsiChar(AnsiString(HostName)));
if Assigned(R) then
begin
A := PInAddr(r^.h_Addr_List^)^;
Result := WinSock.inet_ntoa(A);
end;
end;
Now, observant readers will say:
What if the host name has non-ASCII characters? Isn't it a shame to be constrained by these rather feeble fixed length 8 bit encodings?
Well, the recommended function for translating host name to address nowadays is the Unicode function GetAddrInfoW.
Problem
I have this function that retrieves the IP address if I use `GetIP('server-name')` or `GetIP('google.com')` in my Delphi 2006. But now that I am trying it on `Delphi-XE3` it's not working. Any ideas? ``` function GetIP(const HostName: string): string; var WSAData: TWSAData; R: PHostEnt; A: TInAddr; begin Result := IPNULL; // '0.0.0.0' WSAStartup($101, WSAData); R := Winsock.GetHostByName(PAnsiChar(HostName)); if Assigned(R) then begin A := PInAddr(r^.h_Addr_List^)^; Result := string(WinSock.inet_ntoa(A)); end; end; ``` It seems that `R` is not being assigned because the result is always `'0.0.0.0'`