I'm using TIdStack.LocalAddress to get the local IP address. On an OS X system which has both IP6 and IP4 this returns the IP6 address, which isn't what I want.
What's the best way to find the local IP4 address? I could simply use the shortest entry in TIdStack.LocalAddresses, for example.
The TIdStack.LocalAddress
property simply returns the first IP that is listed in the TIdStack.LocalAddresses
property (note - these properties are deprecated because they are not thread-safe. You should use the TIdStack.AddLocalAddressesToList()
method instead). A PC/device can have multiple local IPs, such as if it is connected to multiple networks, supports both IPv4 and IPv6, etc. The order of the IPs in the LocalAddresses
list is determined by the OS, not by Indy. From the sounds of it, you will have to obtain the complete list and loop through it looking for the IPv4 address you are interested in.
TIdStackVCLPosix
, which Indy uses for Mac OSX, is actually the only TIdStack
implementation that currently supports reporting both IPv4 and IPv6 addresses in the LocalAddresses
property (other TIdStack
implementations only support IPv4 at this time). However, the list is a plain TStrings
, it does not differentiate whether a given IP is IPv4 or IPv6 (it does not use the TStrings.Objects
property to provide that info). If you need to differentiate, you will have to parse the IPs manually. In a future release, Indy will replace the TIdStack.LocalAddress(es)
properties with a different implementation that natively provides the IP version info.
For example:
var
IPs: TStringList;
IP: String;
I: Integer;
Err: Boolean;
begin
IPs := TStringList.Create;
try
GStack.AddLocalAddressesToList(IPs);
for I := 0 to IPs.Count-1 do
begin
IP := IPs[I];
// TIdStack.IsIP() currently only supports IPv4, but
// it will be updated to support IPv6 in a future
// release...
//
// if GStack.IsIP(IP) then
// if GStack.IsIPv4(IP) then
IPv4ToDWord(IP, Err);
if not Err then
Break;
IP := '';
// alternatively:
{
IPAddr := TIdIPAddress.MakeAddressObject(IPs[I]);
IP := IPAddr.IPv4AsString; // returns blank if not IPv4
IPAddr.Free;
if IP <> '' then
Break;
}
end;
finally
IPs.Free;
end;
if IP <> '' then
begin
// use IP as needed...
end;
end;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With