如果ping失败,请发送一次电子邮件

时间:2017-05-09 00:08:59

标签: vb.net email monitoring ping

我正在使用VB.net创建一个监控系统。我希望系统在设备关闭时发送电子邮件,如果该设备重新联机,则再次发送电子邮件。我使用Ping来监控设备。设备的IP地址已保存,并将显示在lvi.SubItems(5).Text中。

使用以下代码,如果设备ping失败,则始终会发送电子邮件。如果ping失败,我只想发送一次电子邮件。你能帮我解决这个问题。

Private Sub Ping_LV()
    For Each lvi As ListViewItem In LV_Monitoring.Items
        Dim p As New Ping
        AddHandler p.PingCompleted, AddressOf p_PingCompleted
        p.SendAsync(lvi.SubItems(5).Text, lvi)
    Next
End Sub

Private Sub p_PingCompleted(ByVal sender As Object, ByVal e As System.Net.NetworkInformation.PingCompletedEventArgs)
    Dim p As Ping = DirectCast(sender, Ping)
    Dim lvi As ListViewItem = DirectCast(e.UserState, ListViewItem)

    If e.Reply.Status = IPStatus.Success Then
        Console.WriteLine("Ping Success")
        lvi.SubItems(6).Text = "UP"
        lvi.UseItemStyleForSubItems = False
        lvi.SubItems(6).ForeColor = Color.White
        lvi.SubItems(6).BackColor = Color.Green
    Else
        Console.WriteLine("Ping Failed")
        lvi.SubItems(6).Text = "DOWN"
        lvi.UseItemStyleForSubItems = False
        lvi.SubItems(6).ForeColor = Color.White
        lvi.SubItems(6).BackColor = Color.Red
        Sent_Email()
    End If

    RemoveHandler p.PingCompleted, AddressOf p_PingCompleted
    p.Dispose()
    LV_Monitoring.Refresh()

End Sub

Private Sub Timer_Tick(sender As Object, e As EventArgs) Handles Timer.Tick
    Ping_LV()
End Sub

Private Sub Form_Monitoring_Devices_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    Timer.Start()
End Sub

1 个答案:

答案 0 :(得分:2)

简单的方法就是将发送邮件的状态保存在变量或属性中。  因此,第一次ping失败并发送电子邮件时,您将变量/ property设置为true,当您的pc再次联机时,您将重置它。如果您更喜欢集合来跟踪这一点,您也可以使用例如字典。

根据要求举例:

    Dim mailSent As New Dictionary(Of String, Boolean)
Dim ipList As New List(Of String) From {"192.168.192.1", "192.168.192.110", "192.168.192.105"}

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    For Each ip In ipList
        Dim p As New Ping
        AddHandler p.PingCompleted, AddressOf PingCompleted
        p.SendAsync(ip, ip)
    Next
End Sub

Private Sub PingCompleted(sender As Object, e As PingCompletedEventArgs)
    Dim p = DirectCast(sender, Ping)
    Dim ip = DirectCast(e.UserState, String)

    If e.Reply.Status = IPStatus.Success Then
        If mailSent.Item(ip) Then
            mailSent.Item(ip) = False
        End If
    Else
        If Not mailSent.Item(ip) Then
            Console.WriteLine(ip & " is offline")
            mailSent.Item(ip) = True
        Else
            Console.WriteLine("You know already " & ip & "state")
        End If
    End If
    RemoveHandler p.PingCompleted, AddressOf PingCompleted
    p.Dispose()
End Sub

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
    For Each ip As String In ipList
        mailSent.Add(ip, False)
    Next
End Sub

这是一个示例,你应该解决它以获得你需要的东西:)