Delphi擷取機器名和IP地址的方法
---
{擷取本機機名}
function GetLocalName():String;
var
CNameBuffer : PChar;
CLen : ^DWord;
begin
GetMem(CNameBuffer,255);
New(CLen);
CLen^:= 255;
if GetComputerName(CNameBuffer,CLen^) then
result:=CNameBuffer
else
result:='';
FreeMem(CNameBuffer,255);
Dispose(CLen);
end;
{根據機名擷取IP,要添加使用單元:WinSock}
function ComputerIP(ComputerName:String):String;
var phe:pHostEnt;
w:TWSAData;
ip_address:longint;
p:^longint;
ipstr:string;
begin
if WSAStartup(2,w)<>0 then exit;
phe:=gethostbyname(pchar(ComputerName));
if phe<>nil then
begin
p:=pointer(phe^.h_addr_list^);
ip_address:=p^;
ip_address:=ntohl(ip_address);
ipstr:=IntToStr(ip_address shr 24)+'.'+IntToStr((ip_address shr 16) and $ff)
+'.'+IntToStr((ip_address shr 8) and $ff)+'.'+IntToStr(ip_address and $ff);
Result :=ipstr;
end;
end;
{擷取本機IP,可獲內網IP或外網IP。也要添加使用單元:WinSock}
Function GetLocalIp(InternetIP:boolean):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;
IP: String;
begin
Screen.Cursor := crHourGlass;
try
WSAStartup($101, GInitData);
IP:='0.0.0.0';
GetHostName(Buffer, SizeOf(Buffer));
phe := GetHostByName(buffer);
if phe = nil then
begin
ShowMessage(IP);
Result:=IP;
Exit;
end;
pPtr := PaPInAddr(phe^.h_addr_list);
if InternetIP then
begin
I := 0;
while pPtr^[I] <> nil do
begin
IP := inet_ntoa(pptr^[I]^);
Inc(I);
end;
end
else
IP := inet_ntoa(pptr^[0]^);
WSACleanup;
Result:=IP;//如果上網則為上網ip否則是網卡ip
finally
Screen.Cursor := crDefault;
end;
end;
{顯示樣本}
procedure TForm1.Button1Click(Sender: TObject);
begin
showmessage('LocalName: '+GetLocalName);
showmessage('LocalIp: '+GetLocalIp(true));
showmessage('ComputerIP: '+ComputerIP(GetLocalName));
end;
--本文來源於[TTT BLOG]:http://www.taoyoyo.net/ttt/post/188.html
(提示:轉載時請務必保留著作權資訊或者註明來源。)