views:

221

answers:

4

HI all....

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

A: 

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

HotTester
A: 

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
@Thomas this code is sending ping successful even if i remove the lan cable from my PC
HotTester
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
A: 

Dear thomas ...many thanks for ur time...

plz tell that how can i handle the time out situation...

Asif
This should be a comment on Thomas' post, not an additional answer.
rwmnau
+1  A: 

Try

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