Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a computer is responding from C#

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.

like image 629
ripper234 Avatar asked Dec 07 '08 13:12

ripper234


2 Answers

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.

like image 22
gimel Avatar answered Sep 18 '22 07:09

gimel


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

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

like image 95
mmx Avatar answered Sep 20 '22 07:09

mmx