仿照@Remy Lebeau在this SO item中非常有用的代码示例,我有以下函数,它在Windows 10中按预期工作以返回;例如:
No of Addresses: 4
IPv4 Addresses:
IP Address #0: 192.168.56.1 - 255.255.255.0 - 11
IP Address #1: 192.168.1.7 - 255.255.255.0 - 8
IP: 192.168.56.1
但是,当我将平台更改为Android 64位并在我的Samsung S21上运行时,同时启用WiFi并连接到我的局域网,它只返回本地环回IP,而不返回任何其他值;例如:
No of Addresses: 1
IPv4 Addresses:
IP Address #0: 127.0.0.1 - - 0
IP: 127.0.0.1
我曾希望这与缺乏一些许可有关,但正如雷米在一条评论中指出的那样,问题是Indy10方法在Android上是错误的,人们需要使用Dave Notage下面的解决方案。如果您还想获得Indy方法应该返回的NetMASK,您可以使用下面发布的我的解决方案作为答案。
function getLocalIP: string;
begin
Result := '';
try
var IPList := TIdStackLocalAddressList.Create;
try
TIdStack.IncUsage;
try
GStack.GetLocalAddressList(IPList);
finally
TIdStack.DecUsage;
end;
WriteLog('DEBUG', 'No of Addresses: ' + IntToStr(IPList.Count));
WriteLog('DEBUG', 'IPv4 Addresses:');
var IPStrings := TStringList.Create;
try
for var i in IPList do
begin
if TIdStackLocalAddressIPv4(i).IPVersion = Id_IPv4 then
begin
IPStrings.Add(TIdStackLocalAddressIPv4(i).IPAddress + ' - ' + TIdStackLocalAddressIPv4(i).SubNetMask
+ ' - ' + TIdStackLocalAddressIPv4(i).InterfaceIndex.ToString);
end;
end;
// show IP Addresses in the log file
for var i := 0 to IPStrings.Count-1 do
WriteLog('DEBUG', 'IP Address #' + IntToStr(i) + ': ' + IPStrings[i]);
Result := IPStrings[0].Split([' - '])[0];
WriteLog('DEBUG', 'IP: ' + Result);
finally
IPStrings.Free;
end;
finally
IPList.Free;
end;
except
On E: Exception do
begin
Result := '';
WriteLog('ERROR', 'IP Error: ' + E.message);
end;
end;
end;
2条答案
按热度按时间knpiaxh11#
根据this gist,但在此重复:
使用风险自负
wecizke32#
以下是我根据@Dave Notage的要点想出的检索Android IPv4地址和子网掩码的方法:
“使用风险自负”:)