一个获取本机ip的函数:
1 class function TGlobal.GetLocalIP: string; 2 type TaPInAddr = array [ 0.. 10] of PInAddr; 3 PaPInAddr = ^TaPInAddr; 4 var phe : PHostEnt; 5 pptr : PaPInAddr; 6 Buffer : array [ 0.. 63] of char; 7 I : Integer; 8 GInitData : TWSADATA; 9 begin 10 WSAStartup($ 101,ginitdata); 11 result := ''; 12 gethostname(buffer,sizeof(buffer)); 13 phe := gethostbyname(buffer); 14 if phe = nil then exit; 15 pptr := papinaddr(phe^.h_addr_list); 16 I := 0; 17 while pptr^[i] <> nil do 18 begin 19 result := SysUtils.StrPas(inet_ntoa(pptr^[i]^)); 20 inc(I); 21 end; 22 WSACleanup; 23 end ;
在delphi2007下编译没有问题。在delphi2010下编译出现错误:E2010 Incompatible types: 'Array' and 'PAnsiChar'
错误定位在第12行。也就是调用gethostname函数出现了错误。根源在于在delphi2010中,gethostname函数的原型发生了改变:
由原来的:function gethostname(name: PChar; len: Integer): Integer; stdcall;
变成了: function gethostname(name: PAnsiChar; len: Integer): Integer; stdcall;
函数做如下修改,编译通过:
1 function GetLocalIP: string; 2 type 3 TaPInAddr = array [ 0.. 10] of PInAddr; 4 PaPInAddr = ^TaPInAddr; 5 const 6 SIZE_HOSTNAME= 250; 7 var 8 phe : PHostEnt; 9 pptr : PaPInAddr; 10 LStr : AnsiString; 11 I : Integer; 12 GInitData : TWSADATA; 13 begin 14 WSAStartup($ 101,ginitdata); 15 result := ''; 16 SetLength(LStr, SIZE_HOSTNAME); 17 gethostname (PAnsiChar(LStr), SIZE_HOSTNAME); 18 phe := gethostbyname(PAnsiChar(LStr)); 19 if phe = nil then exit; 20 pptr := papinaddr(phe^.h_addr_list); 21 I := 0; 22 while pptr^[i] <> nil do 23 begin 24 result := SysUtils.StrPas(inet_ntoa(pptr^[i]^)); 25 inc(I); 26 end; 27 WSACleanup; 28 end ;