C# 程式(軟體)判斷/檢測 網路是否連線

C# 程式(軟體)判斷/檢測 網路是否連線

C# 程式(軟體)判斷/檢測 網路是否連線


資料來源: https://www.itread01.com/content/1546421780.html


Method 1: WebRequest

	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;
        }


Method 2: TCP 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;
            }
        }


Method 3: Ping

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;
            }
        }


Method 4: DNS Lookup

	public static bool DnsTest()
        {
            try
            {
                System.Net.IPHostEntry ipHe =
                    System.Net.Dns.GetHostByName("www.google.com");
                return true;
            }
            catch
            {
                return false;
            }
        }


Method 5: Windows 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);
        }

發表迴響

你的電子郵件位址並不會被公開。 必要欄位標記為 *