thongkorn โพสต์ 2019-3-6 12:50:50

[VB.NET] การใช้คำสั่ง Ping เพื่อตรวจสอบการเชื่อมต่ออุปกรณ์เครือข่าย

http://www.g2gnet.com/webboard/images/vbnet/pingtest.png


โดยปกติเราจะคุ้นเคยกับคำสั่ง Ping ของ DOS Command แต่สำหรับบทความนี้เราจะใช้โค้ดคำสั่งจาก VB.NET มาใช้งานแทนกันครับ โดยที่คลาส Ping ในเนมสเปซ System.Net.NetworkInformation ใช้เพื่อตรวจสอบว่าสามารถเข้าถึงเครื่องระยะไกลผ่านเครือข่ายได้หรือไม่ ในบทความนี้เราจะใช้วิธีการและคุณสมบัติของคลาส Ping เพื่อตรวจสอบความพร้อมใช้งานของเครื่องปลายทาง สำหรับคลาส Ping คล้ายกับคำสั่ง Ping.exe ที่เราใช้ใน DOS Prompt คุณสามารถส่งคำร้องขอ echo Internet Protocol Message Protocol (ICMP) โดยใช้ทั้งวิธีซิงโครนัส และอะซิงโครนัสของคลาส Ping ...

สรุปสาระสำคัญหลักๆ ...
Send() Method เป็นซิงโครนัสเมธอด จะคืนค่า PingReply ตามคำขอของ ICMP
SendAsync() Method เป็นอะซิงโครนัสเมธอด ซึ่งจะใช้เธรดแยกต่างหากเพื่อส่งการร้องขอ
PingCompleted Event จะเกิดขึ้นเมื่อการดำเนินการเสร็จสิ้น และคุณสามารถใช้ PingCompletedEventHandler เพื่อจัดการกับมันได้


มาดูโค้ดกันเถอะ ...
#Region "ABOUT"
' / --------------------------------------------------------------------------
' / Developer : Mr.Surapon Yodsanga (Thongkorn Tubtimkrob)
' / eMail : thongkorn@hotmail.com
' / URL: http://www.g2gnet.com (Khon Kaen - Thailand)
' / Facebook: https://www.facebook.com/g2gnet (For Thailand)
' / Facebook: https://www.facebook.com/commonindy (Worldwide)
' / MORE: http://www.g2gnet.com/webboard
' /
' / Purpose: Ping Test with VB.NET (2010).
' / Microsoft Visual Basic .NET (2010)
' /
' / This is open source code under @CopyLeft by Thongkorn/Common Tubtimkrob.
' / You can modify and/or distribute without to inform the developer.
' / --------------------------------------------------------------------------
#End Region
Imports System.Net
Imports System.Net.NetworkInformation
Imports System.Globalization

Public Class frmPingTest
    Private timer As Timers.Timer

    Private Sub frmPingTest_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
      Call InitListView()
      txtUrl.Text = "192.168.1.60"
    End Sub

    ' / Initailize ListView Control
    Sub InitListView()
      With ListView1
            .Clear()
            .View = View.Details
            .GridLines = True
            .FullRowSelect = True
            .HideSelection = False
            .MultiSelect = False
            ' 1st Column Index = 0
            .Columns.Add("IP Address", ListView1.Width \ 2 + 50)
            .Columns.Add("Response Time", ListView1.Width \ 2 - 70)
      End With
    End Sub

    Private Sub btnConnect_Click(sender As System.Object, e As System.EventArgs) Handles btnConnect.Click
      If Trim(txtUrl.Text) = "" Then Exit Sub
      If isConnected(Trim(txtUrl.Text)) Then
            MessageBox.Show("Connect IP Adress: " & txtUrl.Text, "Report Status", MessageBoxButtons.OK, MessageBoxIcon.Information)
      Else
            MessageBox.Show("Can't Connect.", "Report Status", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
      End If
    End Sub

    ''' <summary>
    ''' check for a existing internet connection to some url.
    ''' </summary>
    ''' <returns>True if it's exist</returns>
    Public Shared Function isConnected(ByVal strURL As String) As Boolean
      Try
            Dim addresslist As IPAddress() = Dns.GetHostAddresses(strURL)
            ' | ' addresslist holds a list of ipadresses to somewhere.
            ' | ' e.g173.194.40.112
            If addresslist(0).ToString().Length > 6 Then
                Return True
            Else
                Return False
            End If
      Catch ex As Sockets.SocketException
            ' | ' You are offline
            ' | ' the host is unkonwn
            Return False
      Catch ex As Exception
            Return False
      End Try
    End Function

    Private Sub btnPing_Click(sender As System.Object, e As System.EventArgs) Handles btnPing.Click
      Dim p As New Ping
      If isConnected(txtUrl.Text) Then
            AddHandler p.PingCompleted, AddressOf PingComplete
            p.SendAsync(txtUrl.Text, "")
      End If
    End Sub

    Private Sub PingComplete(ByVal s As Object, ByVal ev As System.Net.NetworkInformation.PingCompletedEventArgs)
      'ev.Reply.Address.ToString()
      'ev.Reply.RoundtripTime.ToString(CultureInfo.InvariantCulture) + " ms"
      'System.Net.Dns.GetHostEntry(ev.Reply.Address.ToString()).HostName
      Dim LV As ListViewItem
      Dim p As Ping = DirectCast(s, Ping)
      If ev.Reply.Status = IPStatus.Success Then
            LV = ListView1.Items.Add(ev.Reply.Address.ToString())
            LV.SubItems.Add(ev.Reply.RoundtripTime.ToString(CultureInfo.InvariantCulture) + " ms")
      End If
      '// Unforce Event Handler
      RemoveHandler p.PingCompleted, AddressOf PingComplete
      p.Dispose()
    End Sub

    Private Sub txtUrl_KeyPress(sender As Object, e As System.Windows.Forms.KeyPressEventArgs) Handles txtUrl.KeyPress
      If e.KeyChar = Chr(13) Then
            e.Handled = True
            Call btnPing_Click(sender, e)
      End If
    End Sub

    Private Sub frmPingTest_FormClosed(sender As Object, e As System.Windows.Forms.FormClosedEventArgs) Handles Me.FormClosed
      Me.Dispose()
      Application.Exit()
    End Sub

End Class

ดาวน์โหลดโค้ดต้นฉบับ VB.NET (2010) ได้ที่นี่ ...


หน้า: [1]
ดูในรูปแบบกติ: [VB.NET] การใช้คำสั่ง Ping เพื่อตรวจสอบการเชื่อมต่ออุปกรณ์เครือข่าย