Sunday 9 December 2012

Check if network is connected : C#

Recently , there was a situation where we had to check for network availability , following are the ways we achieved it:

Way 1:

Here I am using the In-built method GetIsNetworkAvailable.

The method GetIsNetworkAvailable will considered a network to be connected if the network interface is up.
For this to work your network should not be a tunnel or loopback interface.

You can get more info on tunnel/loopback interface here.

if (System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable())

MessageBox.Show("Hi");

else

MessageBox.Show("Bye")

Way 2:

You can try using the Ping Class

var ping = new Ping();

var options = new PingOptions { DontFragment = true };

//just need some data. this sends 10 bytes.

var buffer = Encoding.ASCII.GetBytes(new string('z', 10));

var host = "Your Host Name";

try



{
 
var reply = ping.Send(host, 60, buffer, options);

if (reply == null)



{
 
MessageBox.Show("Reply was null");

return;



}
 
if (reply.Status == IPStatus.Success)



{
 
MessageBox.Show("Ping was successful.");



}
 
else



{
 
MessageBox.Show("Ping failed.");



}

}
 
catch (Exception ex)



{
 
MessageBox.Show(ex.Message);



}


Way 3:

You can ping a particular IP and see if you are able to connect , you are connected , else you are not connected. You can also give your intranet page name and try to get a response from it as well.

try


{
 
WebRequest request = WebRequest.Create("http://www.google.com");

WebResponse response = request.GetResponse();

StreamReader stream = new StreamReader(response.GetResponseStream());

MessageBox.Show("Hi");



}
 
catch



{
 
MessageBox.Show("Bye");



}

 

No comments:

Post a Comment