Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Check Remote Server

Tags:

c#

.net

Can anyone advise what the best way to check (using .NET 3.5) if a remote server is available?

I was thinking of using the following code but would like to know if a better way exists if the community has another option.

TcpClient client = new TcpClient("MyServer", 80);
if (!client.Connected)
{
    throw new Exception("Unable to connect to MyServer on Port 80");
}
client.Close();
like image 610
Kane Avatar asked Jun 25 '09 11:06

Kane


2 Answers

You could ping it

You could download the default page from it

You could do a HEAD request

If it's a local IIS6 server on your network, and you have some admin details, you could connect to IIS using some DirectoryEntry code

Some of the answers on 136615 might help too, specifically the accepted answer that talks about sockets

For the print servers (or, specifically, the printers), the code by K Scott here might help. It's fun code to play with anyway :-) That code mentions dns.resolve, which is obsoleted and replaced by Dns.GetHostEntry

I'm about out of ideas :-)

like image 53
Dan F Avatar answered Oct 12 '22 08:10

Dan F


If you just want to see whether a given server is online, then a simple ping should do the job in most cases.

PingReply pingReply;
using (var ping = new Ping())
    pingReply = ping.Send("http://www.stackoverflow.com/");
var available = pingReply.Status == IPStatus.Success;

Using this method you're not abusing the HTTP server in any way, too.

Otherwise (if you want to check whether a connection is possible on a specific port), that basically looks fine.

like image 39
Noldorin Avatar answered Oct 12 '22 08:10

Noldorin