Reading response from TIdDNSResolver?

若如初见. 提交于 2019-12-22 17:08:34

问题


I cannot find any simple examples of a DNS lookup using Indy 10's TIdDNSResolver component. They're all either for something I don't need (such as MX/SMTP), or are talking terms with no code. I have tried reading the result based on the few resources I can find, but don't know how I'm supposed to be reading the result.

Here's what I have so far...

uses
  IdBaseComponent, IdComponent, IdTCPConnection, IdDNSResolver;

function TForm1.Lookup(const Name: String): String;
var
  X: Integer;
begin
  //DNS: TIdDNSResolver
  DNS.QueryType:= [qtA];
  DNS.Resolve(Name);
  for X:= 0 to DNS.QueryResult.Count-1 do begin
    if DNS.QueryResult[X].RecType = qtA then
      //Result:= DNS.QueryResult[X].RData;    <--- ????
  end;
end;

usage...

HostIP:= Lookup('www.google.com');

How do I read this response?


回答1:


You will need to typecast the QueryResult collection item to a specific TResultRecord descendant depending on the RecType property value of the item. From the Items property reference:

Use casting to return an object reference that allows access to any properties or method specific to the descendant class associated with the value in TResultRecord.RecType.

The name pattern of the TResultRecord descendant classes is like this:

T<DNS lookup type>Record

So in your case it would look like this:

for X := 0 to DNS.QueryResult.Count - 1 do 
begin
  if DNS.QueryResult[X].RecType = qtA then
    Result := TARecord(DNS.QueryResult[X]).IPAddress; // "A" lookup -> TARecord
end;

For a AAAA lookup type it would be:

for X := 0 to DNS.QueryResult.Count - 1 do 
begin
  if DNS.QueryResult[X].RecType = qtAAAA then
    Result := TAAAARecord(DNS.QueryResult[X]).Address; // "AAAA" lookup -> TAAAARecord
end;

Example functions for IPv4 and IPv6 DNS lookups you may find here.



来源:https://stackoverflow.com/questions/15724253/reading-response-from-tiddnsresolver

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!