在 C# 中检查网络状态

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/314213/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 22:47:35  来源:igfitidea点击:

Checking network status in C#

c#.netnetwork-programming

提问by Brian Clark

How do I check that I have an open network connection and can contact a specific ip address in c#? I have seen example in VB.Net but they all use the 'My' structure. Thank you.

如何检查我是否有一个开放的网络连接并且可以在 c# 中联系特定的 ip 地址?我在 VB.Net 中看到过示例,但它们都使用“我的”结构。谢谢你。

采纳答案by Yona

If you just want to check if the network is up then use:

如果您只想检查网络是否已启动,请使用:

bool networkUp
    = System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable();

To check a specific interface's status (or other info) use:

要检查特定接口的状态(或其他信息),请使用:

NetworkInterface[] networkCards
    = System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces();

To check the status of a remote computer then you'll have to connect to that computer (see other answers)

要检查远程计算机的状态,您必须连接到该计算机(请参阅其他答案)

回答by Lasse V. Karlsen

Well, you would try to connect to the specific ip, and handle denies and timeouts.

好吧,你会尝试连接到特定的 ip,并处理拒绝和超时。

Look at the TcpClient class in the System.Net.Sockets namespace.

查看 System.Net.Sockets 命名空间中的 TcpClient 类。

回答by Patrick Desjardins

First suggestion (IP connection)

第一个建议(IP连接)

You can try to connect to the IP address using something like:

您可以尝试使用以下方法连接到 IP 地址:

IPEndPoint ipep = new IPEndPoint(Ipaddress.Parse("IP TO CHECK"), YOUR_PORT_INTEGER);
Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
server.Connect(ipep);

I suggest you to the check code of a "Chat" program. These programs manipulate a lot of IP connections and will give you a good idea of how to check if an IP is available.

我建议您查看“聊天”程序的校验码。这些程序会操纵大量 IP 连接,并会让您很好地了解如何检查 IP 是否可用。

Second suggestion (Ping)

第二个建议(Ping)

You can try to ping. Here is a good tutorial. You will only need to do:

你可以试试ping。这是一个很好的教程。您只需要执行以下操作:

Ping netMon = new Ping();
PingResponse response = netMon.PingHost(hostname, 4);
if (response != null)
{
    ProcessResponse(response);
}

回答by tamberg

If you're interested in the HTTP status code, the following works fine:

如果您对 HTTP 状态代码感兴趣,以下内容可以正常工作:

using System;
using System.Net;

class Program {

    static void Main () {
        HttpWebRequest req = WebRequest.Create(
            "http://www.oberon.ch/") as HttpWebRequest;
        HttpWebResponse rsp;
        try {
            rsp = req.GetResponse() as HttpWebResponse;
        } catch (WebException e) {
            if (e.Response is HttpWebResponse) {
                rsp = e.Response as HttpWebResponse;
            } else {
                rsp = null;
            }
        }
        if (rsp != null) {
            Console.WriteLine(rsp.StatusCode);
        }
    }

}

Regards, tamberg

问候,坦贝格

回答by CCrawford

If you want to monitor for changes in the status, use the System.Net.NetworkInformation.NetworkChange.NetworkAvailabilityChangedevent:

如果要监视状态的变化,请使用System.Net.NetworkInformation.NetworkChange.NetworkAvailabilityChanged事件:

NetworkChange.NetworkAvailabilityChanged 
    += new NetworkAvailabilityChangedEventHandler(NetworkChange_NetworkAvailabilityChanged);
_isNetworkOnline = NetworkInterface.GetIsNetworkAvailable();


// ...
void NetworkChange_NetworkAvailabilityChanged(object sender, NetworkAvailabilityEventArgs e)
{
    _isNetworkOnline  = e.IsAvailable;
}

回答by akuma6099

My idea was to have a static class/Module to do the monitoring on a spereate thread. A simple DNS resolve will ensure if your network is up and running. Beats ping IMO.

我的想法是有一个静态类/模块来对一个单独的线程进行监控。一个简单的 DNS 解析将确保您的网络是否正常运行。击败 ping IMO。

Imports System.Net

Public Module Network_Monitor

Private InsideWorkNet As Boolean = vbFalse
Private Online_Status As Boolean = vbFalse
Private CurrentWorkIPAddress As New IPHostEntry
Private WithEvents Timer_Online_Check As New Timers.Timer With {.Interval = 5000, .Enabled = True, .AutoReset = True}


Public ReadOnly Property GetOnlineStatus() As String

    Get
        Return Online_Status
    End Get

End Property


Public Sub Initialize()

    Set_Online_Status()
    Timer_Online_Check.Start()

End Sub


Public Sub Set_Online_Status()

    If My.Computer.Network.IsAvailable Then
        Try
            Dim DNSTest As IPHostEntry = Dns.GetHostEntry("google.com")
            If DNSTest.AddressList.Length > 0 Then
                Online_Status = True
            Else : Online_Status = False

            End If

        Catch ex As System.Net.Sockets.SocketException

            Online_Status = False

        End Try
    End If

End Sub


Private Sub Timer_Online_Check_Elaspsed(ByVal sender As Object, ByVal e As Timers.ElapsedEventArgs) Handles Timer_Online_Check.Elapsed
    Set_Online_Status()
End Sub

Public Sub Detect_Work_Network()

    If Online_Status = True Then

        Dim WorkIP As IPHostEntry = New IPHostEntry()

        Try
            WorkIP = Dns.GetHostEntry("serverA.myworkdomain.local")
            If WorkIP.AddressList.Length > 0 Then

                InsideWorkNet = True
                CurrentWorkIPAddress = WorkIP
                'MessageBox.Show(WorkIP.HostName.ToString(), "WorkIP", MessageBoxButtons.OK, MessageBoxIcon.Information)
            End If
        Catch ex As Sockets.SocketException

            Try
                WorkIP = Dns.GetHostEntry("serverA.myworkdomain.com")
                If WorkIP.AddressList.Length > 0 Then

                    InsideWorkNet = False
                    CurrentWorkIPAddress = WorkIP
                    ' MessageBox.Show(WorkIP.HostName.ToString(), "WorkIP", MessageBoxButtons.OK, MessageBoxIcon.Information)
                End If
            Catch ey As Sockets.SocketException

            End Try
        End Try
    End If

End Sub

Public Function GetWorkServerName() As String
    If InsideWorkNet = True Then
        Return "serverA.myworkdomain.local"
    Else : Return "serverA.myworkdomain.com"
    End If


End Function



End Module

I also had to determine if I was inside or outside of my work network. Different servers on each side of the firewall for the app to talk to.

我还必须确定我是在工作网络内部还是外部。防火墙每一侧的不同服务器供应用程序通信。

回答by Amit Kumawat

You can check network status using

您可以使用检查网络状态

if(System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable())
{
  //Do your stuffs when network available

}
else
{
 //Do stuffs when network not available

}