检查网络连接

时间:2010-09-10 18:03:14

标签: c# .net networking

我正在构建一个侦听NetworkAvailibilityChanged事件的简单应用程序。这一切都很好,除了在调制解调器PPP接口连接的情况下,应用程序只有在网络连接时才会收到通知,但在断开连接时却没有通知。

我错过了什么吗?我试过它用于局域网,它工作得很好。

1 个答案:

答案 0 :(得分:3)

以下是NetworkAvailbilityChanged所涉及的内容。

Friend Shared Function InternalGetIsNetworkAvailable() As Boolean
    If ComNetOS.IsWinNt Then
        Dim interface2 As NetworkInterface
        For Each interface2 In SystemNetworkInterface.GetNetworkInterfaces
            If (((interface2.OperationalStatus = OperationalStatus.Up) AndAlso (interface2.NetworkInterfaceType <> NetworkInterfaceType.Tunnel)) AndAlso (interface2.NetworkInterfaceType <> NetworkInterfaceType.Loopback)) Then
                Return True
            End If
        Next
        Return False
    End If
    Dim flags As UInt32 = 0
    Return UnsafeWinINetNativeMethods.InternetGetConnectedState((flags), 0)
End Function

Private Shared Sub ChangedAddress(ByVal sender As Object, ByVal eventArgs As EventArgs)
    SyncLock AvailabilityChangeListener.syncObject
        Dim isNetworkAvailable As Boolean = SystemNetworkInterface.InternalGetIsNetworkAvailable
        If (isNetworkAvailable <> AvailabilityChangeListener.isAvailable) Then
            AvailabilityChangeListener.isAvailable = isNetworkAvailable
            Dim array As DictionaryEntry() = New DictionaryEntry(AvailabilityChangeListener.s_availabilityCallerArray.Count  - 1) {}
            AvailabilityChangeListener.s_availabilityCallerArray.CopyTo(array, 0)
            Dim i As Integer
            For i = 0 To array.Length - 1
                Dim key As NetworkAvailabilityChangedEventHandler = DirectCast(array(i).Key, NetworkAvailabilityChangedEventHandler)
                Dim context As ExecutionContext = DirectCast(array(i).Value, ExecutionContext)
                If (context Is Nothing) Then
                    key.Invoke(Nothing, New NetworkAvailabilityEventArgs(AvailabilityChangeListener.isAvailable))
                Else
                    ExecutionContext.Run(context.CreateCopy, AvailabilityChangeListener.s_RunHandlerCallback, key)
                End If
            Next i
        End If
    End SyncLock
End Sub

根据这些似乎,如果它告诉你有网络,它也应该告诉你没有网络。它似乎也可以解决每个设备的地址问题。当地址发生变化时,它会调用ChangedAddress。

看看这些,看看你是否能更清楚地了解幕后发生的事情。