在C#中检查网络状态

时间:2008-11-24 14:09:56

标签: c# .net network-programming

如何检查我是否有开放的网络连接,并且可以联系c#中的特定IP地址?我在VB.Net中看到了一些例子,但它们都使用了'My'结构。 谢谢。

7 个答案:

答案 0 :(得分:36)

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

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

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

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

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

答案 1 :(得分:13)

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

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


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

答案 2 :(得分:5)

第一个建议(IP连接)

您可以尝试使用以下内容连接到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);

我建议你查看“聊天”程序的代码。这些程序操纵了大量的IP连接,可以让您了解如何检查IP是否可用。

第二个建议(Ping)

您可以尝试ping。这是一个很好的tutorial。你只需要这样做:

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

答案 3 :(得分:3)

如果您对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);
        }
    }

}

此致 tamberg

答案 4 :(得分:2)

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

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

答案 5 :(得分:-1)

我的想法是让一个静态类/模块在一个spereate线程上进行监控。简单的DNS解析将确保您的网络正常运行。 Beats 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

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

答案 6 :(得分:-1)

您可以使用

检查网络状态
if(System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable())
{
  //Do your stuffs when network available

}
else
{
 //Do stuffs when network not available

}