Allen 2009-07-22 16:41:05 14270 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;
 


Tag: Delphi技巧 TTTBLOG
我也要发一个   ·   返回首页   ·   返回[Delphi]   ·   前一个   ·   下一个
欢迎评论
未登录,
请先 [ 注册 ] or [ 登录 ]
(一分钟即可完成注册!)
返回首页     ·   返回[Delphi]   ·   返回顶部