Socket.ReceiveFrom handle with timeout without spam console

I write ServerLocator, which basically translates the port to find a server that will respond IPEndPoint, and I need a search to be able to timeout if nothing is found on the current IPHost, and then go to the next.

Right now I am doing something like this (I deleted some parts of this code, so it only includes what is needed to display my problem. There are also some client bindings)

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 receives spam:

The first exception of type "System.Net.Sockets.SocketException" has appeared in System.dll

? - , ?

.

+3
1

, , . . " ".

, , Visual Studio , . , ( ) , . , , . @Cipi , Release.

+1

Source: https://habr.com/ru/post/1789205/


All Articles