This example demonstrates how to use the Tudpsocket component to get the IP address and host name.
Add a Tudpsocket component to the form, as shown in Figure 1.
Figure 1 Main interface
There are two properties--localhostname and localhostaddr in the Tudpsocket component that store the host name and IP address of the local computer, so add the following response code in the initialization of the form to display the host name and IP address:
procedure TForm1.FormCreate(Sender: TObject);
begin
self.Caption:=UdpSocket1.LocalHostName;
self.Caption:=self.Caption+’:’+UdpSocket1.LocalHostAddr;
end;
The program code is as follows:
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, Sockets, ExtCtrls;
type
TForm1 = class(TForm)
UdpSocket1: TUdpSocket;
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.FormCreate(Sender: TObject);
begin
self.Caption:=UdpSocket1.LocalHostName;
self.Caption:=self.Caption+’:’+UdpSocket1.LocalHostAddr;
end;
end.
Save the file, and then press F9 to run the program, and the results of the program run as shown in Figure 2.