向窗體上添加兩個TLabel組件、兩個TEdit組件和一個TButton組件,設計完成的主界面如圖1所示。
圖1 主界面
首先在程序的uses段中添加對WinSock的引用,然後添加一個GetHostName自定義函數,在其中調用GetComputerName函數獲取計算機名稱,響應代碼如下:
function TfrmMain.GetHostName:String;
var
ComputerName: array[0..MAX_COMPUTERNAME_LENGTH+1] of char;
Size: Cardinal;
begin
result:='';
Size := MAX_COMPUTERNAME_LENGTH+1;
GetComputerName(ComputerName, Size);
Result:=StrPas(ComputerName);
end;
添加一個NameToIP自定義函數,在其中調用GetHostByName函數根據計算機名稱獲取計算機的IP地址,響應代碼如下:
function TfrmMain.NameToIP(Name:string):String;
var
WSAData: TWSAData;
HostEnt: PHostEnt;
begin
result:='';
WSAStartup(2, WSAData);
HostEnt := GetHostByName(PChar(Name));
if HostEnt <> nil then
begin
with HostEnt^ do
result:= Format('%d.%d.%d.%d',[Byte(h_addr^[0]), Byte(h_addr^[1]),Byte(h_addr^[2]), Byte(h_addr^[3])]);
end;
WSACleanup;
end;
程序代碼如下:
unit Unit1;
interface
uses
Windows, Messages, Sys Utils, Variants, Classes, Graphics, Controls, Forms,Dialogs, StdCtrls, WinSock;
type
TfrmMain = class(TForm)
btnStart: TButton;
edtIP: TEdit;
edtName: TEdit;
Label1: TLabel;
Label2: 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 TfrmMain.GetHostName:String;
var
ComputerName: array[0..MAX_COMPUTERNAME_LENGTH+1] of char;
Size: Cardinal;
begin
result:='';
Size := MAX_COMPUTERNAME_LENGTH+1;
GetComputerName(ComputerName, Size);
Result:=StrPas(ComputerName);
end;
procedure TfrmMain.btnStartClick(Sender: TObject);
begin
edtName.Text:=GetHostName;
edtIP.Text:=NameToIP(edtName.Text);
end;
function TfrmMain.NameToIP(Name:string):String;
var
WSAData: TWSAData;
HostEnt: PHostEnt;
begin
result:='';
WSAStartup(2, WSAData);
HostEnt := GetHostByName(PChar(Name));
if HostEnt <> nil then
begin
with HostEnt^ do
result:= Format('%d.%d.%d.%d',[Byte(h_addr^[0]), Byte(h_addr^[1]),
Byte(h_addr^[2]), Byte(h_addr^[3])]);
end;
WSACleanup;
end;
end.
保存文件,然後按F9鍵運行程序,程序運行的初始畫面如圖2所示。
單擊“開始”按鈕,就會獲取並顯示本地計算機的名稱和IP地址。程序運行結果如圖3所示。
圖2 程序運行的初始畫面
圖3 程序運行結果