本程序介绍如何获取本地计算机的名称和IP地址
向窗体上添加两个TLabel组件两个TEdit组件和一个TButton组件设计完成的主界面如图所示
图 主界面首先在程序的uses段中添加对WinSock的引用然后添加一个GetHostName自定义函数在其中调用GetComputerName函数获取计算机名称响应代码如下
function TfrmMainGetHostName:String;
var
ComputerName: array[MAX_COMPUTERNAME_LENGTH+] of char;
Size: Cardinal;
begin
result:=;
Size := MAX_COMPUTERNAME_LENGTH+;
GetComputerName(ComputerName Size);
Result:=StrPas(ComputerName);
end;
添加一个NameToIP自定义函数在其中调用GetHostByName函数根据计算机名称获取计算机的IP地址响应代码如下
function TfrmMainNameToIP(Name:string):String;
var
WSAData: TWSAData;
HostEnt: PHostEnt;
begin
result:=;
WSAStartup( WSAData);
HostEnt := GetHostByName(PChar(Name));
if HostEnt <> nil then
begin
with HostEnt^ do
result:= Format(%d%d%d%d[Byte(h_addr^[]) Byte(h_addr^[])Byte(h_addr^[]) Byte(h_addr^[])]);
end;
WSACleanup;
end;
程序代码如下
unit Unit;
interface
uses
Windows Messages Sys Utils Variants Classes Graphics Controls FormsDialogs StdCtrls WinSock;
type
TfrmMain = class(TForm)
btnStart: TButton;
edtIP: TEdit;
edtName: TEdit;
Label: TLabel;
Label: TLabel;
function GetHostName:String;
procedure btnStartClick(Sender: TObject);
function NameToIP(Name:string):String;
private
{ Private declarations }
public
{ Public declarations }
end;
var
frmMain: TfrmMain;
implementation
{$R *dfm}
function TfrmMainGetHostName:String;
var
ComputerName: array[MAX_COMPUTERNAME_LENGTH+] of char;
Size: Cardinal;
begin
result:=;
Size := MAX_COMPUTERNAME_LENGTH+;
GetComputerName(ComputerName Size);
Result:=StrPas(ComputerName);
end;
procedure TfrmMainbtnStartClick(Sender: TObject);
begin
edtNameText:=GetHostName;
edtIPText:=NameToIP(edtNameText);
end;
function TfrmMainNameToIP(Name:string):String;
var
WSAData: TWSAData;
HostEnt: PHostEnt;
begin
result:=;
WSAStartup( WSAData);
HostEnt := GetHostByName(PChar(Name));
if HostEnt <> nil then
begin
with HostEnt^ do
result:= Format(%d%d%d%d[Byte(h_addr^[]) Byte(h_addr^[])
Byte(h_addr^[]) Byte(h_addr^[])]);
end;
WSACleanup;
end;
end
保存文件然后按F键运行程序程序运行的初始画面如图所示
单击开始按钮就会获取并显示本地计算机的名称和IP地址程序运行结果如图所示
图 程序运行的初始画面
图 程序运行结果