I am writing a ServerLocator that basically broadcast a port to find a server which will respond with an IPEndPoint and I need the search to be able to timeout if nothing is found on the current IPHost and then move on with the next one.
Right now I am doing something like this (I have removed some parts of this code so it only includes what is needed to display my problem. There is also some client bindings going on here)
string serverIp = string.Empty;
while(string.isNullOrEmpty(serverIp))
{
foreach (IPAddress adress in ipHosts.AddressList)
{
using(Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)
{
try
{
client.ReceiveFrom(buffer, ref tempRemoteEP);
//Get server IP
serverIp = tempRemoteEP.ToString().Split(":".ToCharArray(), 2)[0];
break;
}
catch(SocketException e)
{
// We expect connection attempt to time out if we cant find any server on this port and nic. Just continue with the next
if (e.SocketErrorCode == SocketError.TimedOut)
{
continue;
}
}
}
}
}
This works as expected except that the console gets spammed with:
A first chance exception of type 'System.Net.Sockets.SocketException' occurred in System.dll
Is there a good way to handle exceptions like this without spamming the console? Or could I handle this in some other way to be able to avoid the need of exception from timeout?
Thanks.