用C#如何检测给定的网址是否是通路?
比如给个网址为“http://www.163.com”
如何用C#检测是否为可访问状态(也就是连通状态)?
谢谢
------解决方案--------------------解析,超时算是不通
try
{
IPHostEntry host = Dns.GetHostByAddress( "http://www.163.com " );
}
catch
{
//不同
}
------解决方案--------------------用Ping类的Send方法:
public static void SimplePing ()
{
Ping pingSender = new Ping ();
PingReply reply = pingSender.Send ( "www.contoso.com ");
if (reply.Status == IPStatus.Success)
{
Console.WriteLine ( "Address: {0} ", reply.Address.ToString ());
Console.WriteLine ( "RoundTrip time: {0} ", reply.RoundtripTime);
Console.WriteLine ( "Time to live: {0} ", reply.Options.Ttl);
Console.WriteLine ( "Don 't fragment: {0} ", reply.Options.DontFragment);
Console.WriteLine ( "Buffer size: {0} ", reply.Buffer.Length);
}
else
{
Console.WriteLine (reply.Status);
}
}
------解决方案--------------------public class PingExample
{
// args[0] can be an IPaddress or host name.
public static void Main (string[] args)
{
Ping pingSender = new Ping ();
PingOptions options = new PingOptions ();
// Use the default Ttl value which is 128,
// but change the fragmentation behavior.
options.DontFragment = true;
// Create a buffer of 32 bytes of data to be transmitted.
string data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ";
byte[] buffer = Encoding.ASCII.GetBytes (data);
int timeout = 120;
PingReply reply = pingSender.Send (args[0], timeout, buffer, options);
if (reply.Status == IPStatus.Success)
{
Console.WriteLine ( "Address: {0} ", reply.Address.ToString ());
Console.WriteLine ( "RoundTrip time: {0} ", reply.RoundtripTime);
Console.WriteLine ( "Time to live: {0} ", reply.Options.Ttl);
Console.WriteLine ( "Don 't fragment: {0} ", reply.Options.DontFragment);
Console.WriteLine ( "Buffer size: {0} ", reply.Buffer.Length);
}
}
}
------解决方案--------------------应该就是用HttpWebRequest处理,类似下面的代码,这个代码是判断webservice的
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.Method = "GET ";
request.Timeout = Timeout;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode == HttpStatusCode.OK && response.ContentType.Substring(0, 8) == "text/xml ")