In the process of designing a network program, it is often necessary to obtain the name of the host according to the IP address obtained, this example will demonstrate how to obtain the name of the corresponding host according to the IP address entered by the user.
Add two Tlabel components, two tedit components, and a TButton component to the form, as shown in Figure 1 of the finished design.
Figure 1 Main interface
In the process of running the program first need to add Winsock to the uses section of the program, so that you can invoke the Winsock related functions to operate.
Attributes and filename are two global variables. Where the word type's attributes variable is used to store the properties of the file, and the string FileName property is used to store the path and file name of the file.
Additionally, add the following code to the Formcreate procedure:
procedure TfrmMain.btnConversionClick(Sender: TObject);
var
WSAData: TWSAData;
HostEnt: PHostEnt;
IPAddress: string;
addr: dword;
begin
edtName.Clear;
WSAStartup(2, WSAData);
IPAddress:=edtAddress.Text;
try
addr := inet_addr(PChar(IPAddress));
HostEnt:= GetHostByAddr(@addr, Length(IPAddress), PF_INET);
edtName.Text:=HostEnt.h_name;
except
ShowMessage('无效的IP地址');
end;
WSACleanup;
end;