How to check if a computer is responding from C#
-
19-08-2019 - |
Question
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.
Solution
Easy! Use System.Net.NetworkInformation
namespace's ping facility!
http://msdn.microsoft.com/en-us/library/system.net.networkinformation.ping.aspx
OTHER TIPS
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.
As long as you want to check a computer within the own subnet you could check it using ARP. Here's an example:
//for sending an arp request (see pinvoke.net)
[DllImport("iphlpapi.dll", ExactSpelling = true)]
public static extern int SendARP(
int DestIP,
int SrcIP,
byte[] pMacAddr,
ref uint PhyAddrLen);
public bool IsComputerAlive(IPAddress host)
{
//can't check the own machine (assume it's alive)
if (host.Equals(IPAddress.Loopback))
return true;
//Prepare the magic
//this is only needed to pass a valid parameter
byte[] macAddr = new byte[6];
uint macAddrLen = (uint)macAddr.Length;
//Let's check if it is alive by sending an arp request
if (SendARP((int)host.Address, 0, macAddr, ref macAddrLen) == 0)
return true; //Igor it's alive!
return false;//Not alive
}
See Pinvoke.net for more information.