C# check if server is online directly from your code. Check servers or services like web servers, database servers like MySQL and MongoDB. You can probably check a lot of others too using TCP ports. We will need to use the System.Net.Sockets namespace for this function.
using System.Net.Sockets;
ServicePing
We will create a TcpClient and try to connect the the server or service we want to check. If it connects, the server or service is online. If the connection fails the TcpClient will throw an exception. That is how we know if the server or service is offline.
The method will return a bool about the status of the server. It will also take the address and port number as parameters.
public static bool ServicePing(string address, int port)
{
bool serviceOnline;
TcpClient tcpClient = new TcpClient();
try {
tcpClient.Connect(address, port);
serviceOnline = true; // Service is online. No exception thrown.
}
catch(Exception) {
serviceOnline = false; // Exception was thrown. Service is offline
}
return serviceOnline;
}
If we want to check if a web server is online, we check if we can connect to port 80. We can check if google is online by doing something like this.
string address = "google.com";
int port = 80;
if (ServicePing(address, port) == true)
Console.WriteLine("{0}:{1} is online", address, port);
else
Console.WriteLine("{0}:{1} is offline", address, port);
Most of the time this will print out this.
google.com:80 is online
You can check if your MySQL is online. I have one at my home network called db2.home.
string address = "db2.home"; // My internal MySQL server
int port = 3306; // default port for MySQL
if (ServicePing(address, port) == true)
Console.WriteLine("{0}:{1} is online", address, port);
else
Console.WriteLine("{0}:{1} is offline", address, port);
To check out my other C# stuff.