8

I want to ask 2 questions and I would be thankful if somebody can reply.

  1. How can I check (using C#) whether the PC is connected to LAN or not?

  2. How can I check (using C#) my PC is connected on LAN or not

mhu
  • 17,720
  • 10
  • 62
  • 93
Asif
  • 81
  • 1
  • 2
  • 1
    Please see http://stackoverflow.com/questions/314213/checking-network-status-in-c -- if this doesn't answer your question fully, you may want to edit it to make the difference between question #1 and #2 apparent... – mdb Mar 13 '10 at 05:57

3 Answers3

7

Try

System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable()
Bivoauc
  • 853
  • 5
  • 10
3

You want to use Ping to check whether a PC is connected to the LAN. Here's a sample:

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 = "127.0.0.1";

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 );
}

To check if you own machine was connected, you could do the same to an address you know should resolve like say the domain controller.

Thomas
  • 63,911
  • 12
  • 95
  • 141
  • 1
    @Thomas this code is sending ping successful even if i remove the lan cable from my PC – HotTester Mar 13 '10 at 06:09
  • 2
    That's because I used 127.0.0.1 merely for illustration purposes. You would need to replace that IP with one on the network like say a domain controller. – Thomas Mar 13 '10 at 16:57
1

Use System.Net.NetworkInformation namespace's ping facility. For more refer this link

HotTester
  • 5,620
  • 15
  • 63
  • 97