While working with window application or web application we may require to call external server for some data. Before calling that external server from application first we have to check whether that server is available or not, that means first we have to ping that server to find availability of that server. In this article we discuss how to ping the external server from the C# application.
System.Net.NetworkInformation namespace helps you to ping the external server. Open Microsoft Visual Studio 2013 => create simple windows application and change the code as shown below.
using System;
using System.Net.NetworkInformation;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
if (PingMachine("home-pc"))
{
MessageBox.Show("Server is available");
}
else
{
MessageBox.Show("Server is not available");
}
}
private static bool PingMachine(string serverName)
{
try
{
Ping sender = new Ping();
PingOptions options = new PingOptions();
options.DontFragment = true;
string data = "test data";
byte[] buffer = Encoding.ASCII.GetBytes(data);
int timeout = 2500;
PingReply reply = sender.Send(serverName, timeout, buffer, options);
return reply.Status == IPStatus.Success ? true : false;
}
catch
{
return false;
}
}
}
}
As shown above we are using Ping class of System.Net.NetworkInformation namespace to check whether server is available or not by sending some text data. If the server is available PingMachine() method returns True otherwise it returns false.