views:

1315

answers:

2

What is the easiest way to check if a computer is alive and responding (say in ping/NetBios)? I'd like a deterministic method that I can time-limit.

One solution is simple access the share (File.GetDirectories(@"\compname")) in a separate thread, and kill the thread if it takes too long.

+5  A: 

Easy! Use System.Net.NetworkInformation namespace's ping facility!

http://msdn.microsoft.com/en-us/library/system.net.networkinformation.ping.aspx

Mehrdad Afshari
For security reason PING is one of the services that blocked at our network boundary -- along with a variety of other ports. If available this is a good mechanism, but you'd have to know if it was going to work first and that it won't be turned off in the future.
tvanfosson
In fact, this can happen to any service. Therefore, if you need reliable way to reach a service on a remote computer, you should probably consider checking it at a higher level protocol (the protocol you're specifically relying on).
Mehrdad Afshari
@Mehrdad - Agreed.
tvanfosson
+1  A: 

To check a specific TCP port (myPort) on a known server, use the following snippet. You can catch the System.Net.Sockets.SocketException exception to indicate non available port.

using System.Net;
using System.Net.Sockets;
...

IPHostEntry myHostEntry = Dns.GetHostByName("myserver");
IPEndPoint host = new IPEndPoint(myHostEntry.AddressList[0], myPort);

Socket s = new Socket(AddressFamily.InterNetwork,
    SocketType.Stream, ProtocolType.Tcp);
s.Connect(host);

Further, specialized, checks can try IO with timeouts on the socket.

gimel