获取本地计算机的名称和IP地址
前言:这是网上找一个例子,我用来熟悉一下delphi 语言的.
这个程序不难,主要是就练习了,函数调用返回,与winsock 调用什么的.
我就是练习了一下,文字比较少,要看不明白再问我吧.
本程序介绍如何获取本地计算机的名称和IP地址。
向窗体上添加两个TLabel组件、两个TEdit组件和一个TButton组件,设计完成的主界面如图所示。
首先在程序的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;
inte易做图ce
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, WinSock;
type
TfrmMain = class(TForm)
edtIP: TEdit;
edtName: TEdit;
Label1: TLabel;
Label2: TLabel;
btnStart: TButton;
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.
补充:综合编程 , 安全编程 ,