最近在网上下了如下代码,可测试时总报错误(access violation at .....)!
请大家帮助看看!function GetLocalIP:string; //获取本机IP地址
type
   TaPInAddr = array[0..255] of PInAddr; //Use Winsock.pas
   PaPInAddr = ^TaPInAddr;
var
   phe: PHostEnt;
   pptr: PaPInAddr;
   Buffer: array[0..63] of char;
   i: integer;
   GInitData: TWSADATA;
begin
   wsastartup($101, GInitData);
   result := '';
   GetHostName(Buffer,SizeOf(Buffer));
   phe:=GetHostByName(buffer);
   if not assigned(phe) then exit;
   pptr:=PaPInAddr(Phe^.h_addr_list);
   i:=0;
   while pptr^[I]<>nil do
   begin
     result:=Result+StrPas(inet_ntoa(pptr^[I]^))+',';
     inc(i);
   end;
   Delete(Result,Length(Result),1);
   wsacleanup;
end;

解决方案 »

  1.   

    我的还是delphi6,单独建立一个工程还是报同样的错误啊!奇怪!!!
      

  2.   

    可以跟踪测试到底是哪一条代码错了,找到了错误的地方,再来
    分析原因吗?就这样说错了,如果是DELPHI环境引起的,别人怎
    么知道错在哪条代码?
      

  3.   

    uses winsock
    .......
    Function   LocalIP: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;   
      begin   
      result:='';   
      wsastartup($101,ginitdata);   
      try   
      gethostname(buffer,sizeof(buffer));   
        phe:=gethostbyname(buffer);   
        if   phe<>nil   then   
        begin   
        pptr:=papinaddr(phe^.h_addr_list);   
        I:=0;   
        while   pptr^[i]<>nil   do   
        begin   
        result:=strpas(inet_ntoa(pptr^[i]^));   
        inc(i);   
        end;   
        end;   
        finally   
        wsacleanup;   
        end;   
        end;   
    procedure TForm3.FormCreate(Sender: TObject);
    begin
     label2.Caption:='本地IP地址是:'+localIP;   //取出IP
    end;
      

  4.   

    楼上的代码可用!!谢谢
    原因是:我原来的是uses IDwinsock
    正确的应该是uses winsock 同时谢谢大家!