tags:

views:

2248

answers:

4

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 around converting them to delphi.

+5  A: 

If you are using ICS for socket communication, you can use LocalIPList function, defined in the OverbyteIcsWSocket unit.

Even if you are not using it, you can download the source code and look up the implementation. It uses WinSock internally.

gabr
thankyou, you gave me the hint i needed, im using indy9 so i had a snoop around there and found my answer :)
Christopher Chase
A: 
Mick
+1  A: 

in indy 9, there is a unit IdStack, with the class TIdStack

fStack := TIdStack.CreateStack;
try
  edit.caption := fStack.LocalAddress;  //the first address i believe
  ComboBox1.Items.Assign(fStack.LocalAddresses); //all the address'
finally
  freeandnil(fStack); 
end;

works great :)

from Remy Lebeau's Comment

The same exists in Indy 10, but the code is a little different:

TIdStack.IncUsage; 
try 
  GStack.AddLocalAddressesToList(ComboBox1.Items); 
  Edit.Caption := ComboBox1.Items[0]; 
finally 
  TIdStack.DecUsage; 
end;
Christopher Chase
The same exists in Indy 10, but the code is a little different:TIdStack.IncUsage;try GStack.AddLocalAddressesToList(ComboBox1.Items); Edit.Caption := ComboBox1.Items[0];finally TIdStack.DecUsage; end;
Remy Lebeau - TeamB
A: 

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;
Remko