Delphi, How to get all local IPs?

前端 未结 6 1675
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-03 07:47

Any one know a way in delphi get a simple list (eg tstrings) of the local ip address.

I have had a look at the other related question, and cant seem to get my head a

6条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-03 08:23

    It can also be done by using WinApi (necessary headers are in the Jedi ApiLib). This is how I do it in my TSAdminEx application:

    function EnumerateIpAddresses(var IPList: TStringList): Boolean;
    var
      IPAddrTable: PMIB_IPADDRTABLE;
      Size: DWORD;
      Res: DWORD;
      Index: Integer;
      Addr: IN_ADDR;
    begin
      Result := False;
    
      IPList.Duplicates := dupIgnore;
    
      Size := 0;
      // Get required Size
      if GetIpAddrTable(nil, Size, False) <> ERROR_INSUFFICIENT_BUFFER then Exit;
    
      // Reserve mem
      GetMem(IPAddrTable, Size);
      Res := GetIpAddrTable(IPAddrTable, Size, True);
    
      if Res <> NO_ERROR then Exit;
    
      for Index := 0 to IPAddrTable^.dwNumEntries-1 do
      begin
        // Convert ADDR to String and add to IPList
        Addr.S_addr := IPAddrTable^.table[Index].dwAddr;
        // Prevent implicit string conversion warning in D2009 by explicit cast to string
        IPList.Add({$IFDEF UNICODE}String({$ENDIF UNICODE}inet_ntoa(Addr){$IFDEF UNICODE}){$ENDIF UNICODE});
      end;
    
      // Free Mem
      FreeMem(IPAddrTable);
    
      Result := True;
    end;
    

提交回复
热议问题