Gallery
Software
Music
Programming
Archive
Friday, Jul 19 Week 29
When successfully looking up DNS hostname for IP-addresses, it returns a -
domain name, often with country code extension and other useful information.
Automatically detecting if to lookup hostname or IP-address.
By giving valid IP address syntax it will lookup hostname, and -
by giving a hostname it will lookup the IP address.

function dnsLookUp(p:pAnsiChar):ansiString;
function validIp(p:pAnsiChar):boolean;
function pCopy(p:pAnsiChar;n:longWord):ansiString;
function pLen(p:pAnsiChar):longWord;
function ipToInt(p:pAnsiChar;aLen:longWord):longWord;

implementation

{$R *.dfm}

uses
winSock;

const
NULL = #0; //Blank char
NONE = $00; //Blank number

function dnsLookUp(p:pAnsiChar):ansiString;
var wsa:tWsaData;n:longWord;rP:pHostEnt;
begin
if (p=nil) or (p^=NULL) then begin result:='';exit end;
result:=pCopy(p,pLen(p));
if wsaStartUp(1 or 0 shl 8,wsa)NOERROR then exit;
if validIp(p) then begin
n:=ipToInt(p,pLen(p));//ip to host
rP:=getHostByAddr(@n,4,AF_INET);
if rPnil then result:=rP^.h_name;
end else begin //host to ip
rP:=getHostByName(p);
if rPnil then result:=inet_ntoa(pInAddr(rP^.h_addr^)^);
end;
wsaCleanUp;
end;

function validIp(p:pAnsiChar):boolean;
var lP:pAnsiChar;i,e:longInt;b:byte;
begin
result:=false;
b:=0;
lP:=p;
while p^NULL do begin
case p^ of
'0'..'9':;//accept.
'.':begin
val(pCopy(lP,p-lP),i,e);
if (e0) or (i>$FF) then exit;
inc(b);lP:=p+1;
end;
else exit end;
inc(p);
end;
if b3 then exit;
val(pCopy(lP,p-lP),i,e);
if (e=0) and (i0 do begin rP^:=p^;inc(rP);inc(p);dec(n) end;
end;

function pLen(p:pAnsiChar):longWord;
var p1:pAnsiChar;
begin
if p=nil then begin result:=0;exit end;
p1:=p;
while p^NULL do inc(p);
result:=p-p1;
end;

function ipToInt(p:pAnsiChar;aLen:longWord):longWord;
var q,b:byte;lP:pAnsiChar;e:integer;
begin
result:=0;
q:=0;
lP:=p;
while aLen0 do begin
if p^='.' then begin
val(pCopy(lP,p-lP),b,e);if e0 then b:=0;
inc(result,b shl q);if q>$10 then break;inc(q,8);
lP:=p+1;
end;inc(p);dec(aLen)
end;
if q>$18 then exit;
val(pCopy(lP,p-lP),b,e);
if e=NONE then inc(result,b shl q);
end;

Example

procedure TForm1.FormCreate(Sender: TObject);
var s:ansiString;
begin
s:='google.com';
caption:=dnsLookUp(pAnsiChar(s)); //ip to hostname
end;

Related pages of DNS Lookup, IP and host name

Remove HTML from text
Download file using Indy HTTP
Download HTML-source using Indy HTTP
Valid IP address syntax
Convert between IPv4 and string
Delphi programming
Programming
Delphi examples
IP-address register
TCP-IP Scanner 1.0