如题

解决方案 »

  1.   

    use 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
      WSAStartup($101,GInitData);
      Result:='';
      GetHostName(Buffer,SizeOf(Buffer));
      phe := GetHostByName(Buffer);
      if phe = nil then Exit;
      pptr :=PaPInAddr(Phe^.h_addr_list);
      i:=0;
      while pptr^[i]<>nil do
      begin
        result:=Strpas(inet_ntoa(pptr^[i]^));
        inc(i);
      end;
      WSACleanup;
    end;
      

  2.   

    以下代码可得到IP和子网掩码:
    结果在变参中,返回值是我程序的错误代码,你自己改吧
    function TGbnSock.GetIPInfo(var aIP:String;var aMask:String):Integer;
    var
      aReg:TRegistry;
      aRE:Boolean;
      aRegBuf,aIPBuf:PChar;
      aDevice:String;
      aAdapter:String;
    begin
      aReg:=TRegistry.Create;
      try
        aReg.RootKey:=HKEY_LOCAL_MACHINE;
        aRE:=aReg.OpenKey('SYSTEM\CurrentControlSet\Services\Tcpip\Linkage',false);
        if aRE then
        begin
          GetMem(aRegBuf,1024);
          aReg.ReadBinaryData('Bind',aRegBuf^,1024);
          aDevice:=strpas(aRegBuf);
          FreeMem(aRegBuf);
          aReg.CloseKey;
        end else
        begin
          Result:=7003;
          aReg.CloseKey;
          aReg.Free;
          Exit;
        end;
        aAdapter:=Copy(aDevice,2,Length(aDevice)-1);
        aAdapter:=Copy(aAdapter,POS('\',aAdapter)+1,Length(aAdapter)-POS('\',aAdapter));
        aRE:=aReg.OpenKey('SYSTEM\CurrentControlSet\Services\'+aAdapter+'\Parameters\Tcpip',false);
        if aRE then
        begin
          GetMem(aRegBuf,1024);
          aReg.ReadBinaryData('SubnetMask',aRegBuf^,1024);
          aMask:=strpas(aRegBuf);
          FreeMem(aRegBuf);
          GetMem(aIPBuf,1024);
          aReg.ReadBinaryData('IPAddress',aRegBuf^,1024);
          aIP:=strpas(aIPBuf);
          FreeMem(aIPBuf);
        end else
        begin
          Result:=7004;
          aReg.CloseKey;
          aReg.Free;
          Exit;
        end;
      finally
        aReg.CloseKey;
        aReg.Free;
      end;
      Result:=0;
    end;
      

  3.   

    短而实用
    可以得到ip和主机名
    procedure GetHost(var Name, Address: string);
    var
    WSAData: TWSAData;
    HostEnt: PHostEnt;
    begin
    WSAStartup(2, WSAData);
    SetLength(Name, 255);
    Gethostname(PChar(Name), 255);
    SetLength(Name, StrLen(PChar(Name)));
    HostEnt := gethostbyname(PChar(Name));
    with HostEnt^ do
    Address := Format('%d.%d.%d.%d',[Byte(h_addr^[0]),
    Byte(h_addr^[1]),Byte(h_addr^[2]), Byte(h_addr^[3])]);
    WSACleanup;
    end;
      

  4.   

    调用方法
    var
    name,ip:string;
    begin
    gethost(name,ip);
    end