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
(提示:转载时请务必保留版权信息或者注明来源。)
|
请发表评论