delphi5中如何取得本地计算机的主机名和IP地址(20分)

  • 主题发起人 主题发起人 xuwensheng
  • 开始时间 开始时间
X

xuwensheng

Unregistered / Unconfirmed
GUEST, unregistred user!
delphi5中如何取得本地计算机的主机名和IP地址
 
BOOL GetComputerName(
LPTSTR lpBuffer, // computer name
LPDWORD lpnSize // size of name buffer
);
Parameters
lpBuffer
[out] Pointer to a buffer that receives a null-terminated string containing the computer name. The buffer size should be large enough to contain MAX_COMPUTERNAME_LENGTH + 1 characters.
lpnSize
[in/out] On input, specifies the size, in TCHARs, of the buffer. On output, receives the number of TCHARs copied to the destination buffer, not including the terminating null character.
If the buffer is too small, the function fails and GetLastError returns ERROR_BUFFER_OVERFLOW.

Windows 95/98: GetComputerName fails if the input size is less than MAX_COMPUTERNAME_LENGTH + 1.

Return Values
If the function succeeds, the return value is a nonzero value.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks
The GetComputerName function retrieves the NetBIOS name established at system startup. Name changes made by the SetComputerName or SetComputerNameEx functions do not take effect until the user restarts the computer.

Requirements
Windows NT/2000: Requires Windows NT 3.1 or later.
Windows 95/98: Requires Windows 95 or later.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

 
user winsock;

//取得本地IP
function GetLocalIP:String;
type
TaPInAddr = array [0..10] of PInAddr;
PaPInAddr = ^TaPInAddr;
var
phe : PHostEnt;
pptr : PaPInAddr;
Buffer : array [0..63] of char;
I : Integer;
GInitData : TWSADATA;

begin
WSAStartup($101, GInitData);
try
Result:='';
GetHostName(Buffer, SizeOf(Buffer));
phe :=GetHostByName(buffer);
if phe = nil then Exit;
pptr := PaPInAddr(Phe^.h_addr_list);
I := 0;
while pptr^ <> nil do
begin
result:=StrPas(inet_ntoa(pptr^^));
Inc(I);
end;
finally
WSACleanup;
end;
end;


//取得计算机名

function GetComputerName:string;
var
pComputerName:PChar;
ComputerNameLen:DWORD;
begin
ComputerNameLen:=255;
GetMem(pComputerName,ComputerNameLen);
try
if not GetComputerName(pComputerName,ComputerNameLen) then
pComputerName:='没有计算机名';
ComputerName:=String(PComputerName);
finally
FreeMem(pComputerName);
End;
result:=ComputerName;
End;

哈哈,给分。

 
太复杂了,从注册表中找
procedure TForm1.Button1Click(Sender: TObject);
var
Reg: TRegistry;
H:STRING;
begin
Reg := TRegistry.Create;
try
Reg.RootKey := HKEY_LOCAL_MACHINE;
if Reg.OpenKey('/SYSTEM/CURRENTCONTROLSET/CONTROL/COMPUTERNAME/COMPUTERNAME', True)
then
h:=Reg.ReadString('computername');
finally
Reg.CloseKey;
Reg.Free;
form1.Caption :=h;

end;
end;
得到计算机名称
 
从注册表找的方法好像并不适用于所有的吧?Windows 95 的注册表好像不太全。
最好还是用正规的 API 调用。
 
api好像只支持 登录了网络的 系统
 
林沐 的回答基本正确 但是取主机名的函数GetComputerName第一个参数如果是 PCHAR
类型时,有时会有间题.应改为:array [0..254] of char 类型。然后调用时参数前加@
 
后退
顶部