Allen 2009-07-22 16:41:05 14344 0 0 0 0

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;
 


【版權聲明】
本文爲原創,遵循CC 4.0 BY-SA版權協議!轉載時請附上原文鏈接及本聲明。
原文鏈接:https://tdlib.com/am.php?t=fgfSE4EcWfR4
Tag: Delphi技巧 TTTBLOG
我也要發一個   ·   返回首頁   ·   返回[Delphi]   ·   前一個   ·   下一個
歡迎評論
未登錄,
請先 [ 註冊 ] or [ 登錄 ]
(一分鍾即可完成註冊!)
返回首頁     ·   返回[Delphi]   ·   返回頂部