I have an IP discover method where I test every IP address with a TcpClient
, when any IP has a successful connection I set the WebServerIp
in the memory, and that's when in my world the task is completed successfully. Is there a way to implement it here in my code? Or some kind of cancelation token when a task is "successful".
Here is my code:
public async Task<bool> DiscoverDeviceAsync()
{
var ips = GeneralService.GetIPAddress();
PhoneIp = string.Join(",", ips.Select(x => x.ToString()));
await Task.Delay(1000);
var tasks = new List<Task>();
foreach (IPAddress ip in ips)
{
byte[] ipBytes = ip.GetAddressBytes();
for (int i = 0; i <= 254; i++)
{
ipBytes[3] = (byte)i;
IPAddress currentIPAddress = new(ipBytes);
tasks.Add(ScanIPAddress(currentIPAddress, 9431));
}
}
await Task.WhenAny(tasks);
return WebServerIp != "";
}
async Task ScanIPAddress(IPAddress ipAddress, int port)
{
try
{
using TcpClient tcpClient = new()
{
SendTimeout = 100,
ReceiveTimeout = 100,
};
await tcpClient.ConnectAsync(ipAddress, port);
WebServerIp = ipAddress.ToString();
}
catch
{
throw new Exception($"No device found at address: {ipAddress}");
}
}