Delphi擷取機器名和IP(包括內網和外網)地址的方法

來源:互聯網
上載者:User

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

 

(提示:轉載時請務必保留著作權資訊或者註明來源。)

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.