熱點推薦:
您现在的位置: 電腦知識網 >> 編程 >> Delphi編程 >> 正文

用Delphi獲取本地計算機名稱和IP地址

2013-11-11 21:04:12  來源: Delphi編程 
本程序介紹如何獲取本地計算機的名稱和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地址程序運行結果如圖所示
  
 

  
程序運行的初始畫面

  

  
程序運行結果

From:http://tw.wingwit.com/Article/program/Delphi/201311/8404.html
    Copyright © 2005-2013 電腦知識網 Computer Knowledge   All rights reserved.