转:https://blog.csdn.net/xuexiaodong009/article/details/81907821
C# 如何检测网络连接
1WebRequest
public static bool WebRequestTest() { string url = "http://www.google.com"; try { System.Net.WebRequest myRequest = System.Net.WebRequest.Create(url); System.Net.WebResponse myResponse = myRequest.GetResponse(); } catch (System.Net.WebException) { return false; } return true; }
2TCP Socket
public static bool TcpSocketTest() { try { System.Net.Sockets.TcpClient client = new System.Net.Sockets.TcpClient("www.google.com", 80); client.Close(); return true; } catch (System.Exception ex) { return false; } }
3Ping
public bool PingTest() { System.Net.NetworkInformation.Ping ping = new System.Net.NetworkInformation.Ping(); System.Net.NetworkInformation.PingReply pingStatus = ping.Send(IPAddress.Parse("208.69.34.231"),1000); if (pingStatus.Status == System.Net.NetworkInformation.IPStatus.Success) { return true; } else { return false; } }
4DNS Lookup
public static bool DnsTest() { try { System.Net.IPHostEntry ipHe = System.Net.Dns.GetHostByName("www.google.com"); return true; } catch { return false; } }
5Windows Internet API (WinINet)
[DllImport("wininet.dll")] private extern static bool InternetGetConnectedState(out int connDescription, int ReservedValue); //check if a connection to the Internet can be established public static bool IsConnectionAvailable() { int Desc; return InternetGetConnectedState(out connDesc, 0); }