Search code examples
c#sql-serverwinformsmonitoringdetection

Real-Time monitoring of Network State. What events are raised?


I have a winform app that needs to be aware of when a SQL server is available so as to allow the Merge Syncing functionality. I have tried variations of the below, which work on a one time basis, but I would like to come up with something a little more dynamic.

The below funcion(Thank you Alex_L) is checking for the 1433 port that SQL runs on and works great. What I am trying to accomplish is a way to monitor this in Real-Time. Would I have to create a Windows Service? What about any other network events like the Network Connection changing?

The usage of this sometimes connected app is simple. If they are on our network then the Merge Replication portion is available. If they are not on our network then it is not. The SQL Server should never be available of our network and it SHOULD always be available when on.

That being said, I would be open to solutions involing detecting our current network in lieu of the SQL instance.

     private static bool IsSqlAvailable()
        {
            TcpClient tcpc = new TcpClient();
             try
               {
                 tcpc.Connect("10.250.50.30", 1433);
                 return true;
               }
             catch
               {
                 return false;
               }
        }

Solution

  • You can check port 1433 of SQL Server (or another, if used):

    TcpClient tcpc = new TcpClient();
    try
    {
        tcpc.Connect("10.250.50.30", 1433);
        return true;
    }
    catch
    {
        return false;
    }