向窗体上添加一个TUdpSocket组件,如图1所示。
图1 主界面 |
TUdpSocket组件中有两个属性——LocalHostName和LocalHostAddr,其中分别存储了本地计算机的主机名和IP地址,所以在窗体的初始化中添加如下响应代码来显示主机名和IP地址:
procedure TForm1.FormCreate(Sender: TObject); begin self.Caption:=UdpSocket1.LocalHostName; self.Caption:=self.Caption+’:’+UdpSocket1.LocalHostAddr; end; |
程序代码如下:
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. |
保存文件,然后按F9键运行程序,程序运行结果如图2所示。