在delphi中,如何得到本机的名字和IP地址(在局域网中)。(50分)

  • 主题发起人 主题发起人 zycczwf
  • 开始时间 开始时间
Z

zycczwf

Unregistered / Unconfirmed
GUEST, unregistred user!
如上所述,谢谢。
 
function getIP: TStrings;
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);
Result:=TStringList.Create;
Result.Clear;
GetHostName(Buffer, SizeOf(Buffer));
phe := GetHostByName(buffer);
if phe = nil then
begin
Exit;
end;
pPtr := PaPInAddr(phe^.h_addr_list);
I := 0;
while pPtr^ <> nil do
begin
Result.Add(inet_ntoa(pptr^^));
Inc(I);
end;
WSACleanup;
end;


BOOL GetComputerName(
LPTSTR lpBuffer, // address of name buffer
LPDWORD nSize // address of size of name buffer
);
 
uses {...,}Winsock;

procedure ShowHostName;
var
wVersionRequested : WORD;
wsaData : TWSAData;
p : PHostEnt;
s : array[0..128] of char;
p2 : pchar;
begin
{启动 WinSock}
wVersionRequested := MAKEWORD(1, 1);
WSAStartup(wVersionRequested, wsaData);

{计算机名}
GetHostName(@s, 128);
p := GetHostByName(@s);
ShowMessage(Format('Computer name is ''%s''.', [p^.h_Name]));

{IP地址}
p2 := iNet_ntoa(PInAddr(p^.h_addr_list^)^);
ShowMessage(Format('IP address is %s.',[p2]));

WSACleanup;
end;
 
snjat的方法很好用,非常方便。
 
function GetLocalComputerName: string;
var
Count: DWORD;
begin
Count := MAX_COMPUTERNAME_LENGTH + 1;
// set buffer size to MAX_COMPUTERNAME_LENGTH + 2 characters for safety
SetLength(Result, Count);
Win32Check(GetComputerName(PChar(Result), Count));
SetLength(Result, StrLen(PChar(Result)));
end;

function GetIPAddress(const HostName: string): string;
var
R: Integer;
WSAData: TWSAData;
HostEnt: PHostEnt;
Host: string;
SockAddr: TSockAddrIn;
begin
Result := '';
R := WSAStartup(MakeWord(1, 1), WSAData);
if R = 0 then
try
Host := HostName;
if Host = '' then
begin
SetLength(Host, MAX_PATH);
GetHostName(PChar(Host), MAX_PATH);
end;
HostEnt := GetHostByName(PChar(Host));
if HostEnt <> nil then
begin
SockAddr.sin_addr.S_addr := Longint(PLongint(HostEnt^.h_addr_list^)^);
Result := inet_ntoa(SockAddr.sin_addr);
end;
finally
WSACleanup;
end;
end;
 
snjat,really a goodman! thanks a lot.
 
多人接受答案了。
 
后退
顶部