Mega Code Archive

 
Categories / Delphi / LAN Web TCP
 

How to get a ip address of a domain name

{ You must be connected to the internet and don't forget to add this unit to get it to work :-) } unit Unit1; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs,winsock, StdCtrls; type TForm1 = class(TForm) Button1: TButton; Edit1: TEdit; procedure Button1Click(Sender: TObject); private { Private declarations } public function ConvertDomainIP( sHost:string): Boolean; { Public declarations } end; type TName = array[0..100] of Char; PName = ^TName; var Form1: TForm1; sErrorWAS:string; implementation {$R *.dfm} function Tform1.ConvertDomainIP( sHost:string): Boolean; var HEnt: pHostEnt; HName: PName; WSAData: TWSAData; sIPAddr, sWSAError: string; iCnt,i: Integer; begin Result := False; if WSAStartup($0101, WSAData) <> 0 then begin sWSAError := 'WSAStartup error'; Exit; end; sIPAddr := ''; sWSAError := ''; New(HName); for i:=0 to length(sHost) do HName^[i]:=shost[i+1]; HEnt := GetHostByName(HName^); if HEnt <> nil then begin Result := True; for iCnt := 0 to HEnt^.h_length - 1 do sIPAddr := sIPAddr + IntToStr(Ord(HEnt^.h_addr_list^[iCnt])) + '.'; SetLength(sIPAddr, Length(sIPAddr) - 1); edit1.Text :=sIPAddr; //displays the IP address of the domain name end else begin result :=false; case WSAGetLastError of // possible errors to display WSANOTINITIALISED: sWSAError := 'A successful WSAStartup must occur before using this function.'; WSAENETDOWN: sWSAError := 'The network subsystem has failed.'; WSAHOST_NOT_FOUND: sWSAError := 'Authoritative Answer Host not found.'; WSATRY_AGAIN: sWSAError := 'Non-Authoritative Host not found, or server failed.'; WSANO_RECOVERY: sWSAError := 'Nonrecoverable error occurred.'; WSANO_DATA: sWSAError := 'Valid name, no data record of requested type.'; WSAEINPROGRESS: sWSAError := 'A blocking Windows Sockets 1.1 call is in progress, or the ' + 'service provider is still processing a callback function.'; WSAEAFNOSUPPORT: sWSAError := 'The type specified is not supported by the Windows '+ 'Sockets implementation.'; WSAEFAULT: sWSAError := 'The addr parameter is not a valid part of the user address '+ 'space, or the len parameter is too small.'; WSAEINTR: sWSAError := 'A blocking Windows Socket 1.1 call was canceled through '+ 'WSACancelBlockingCall.'; else sWSAError := 'UNKNOWN'; end; sErrorWAS :=sWSAError; end; Dispose(HName); WSACleanup; end; procedure TForm1.Button1Click(Sender: TObject); begin if ConvertDomainIP(edit1.text) then showmessage('Okay') else showmessage('NO! '+sErrorWAS); end; end.