We all know that it was cake with VB6. And I'm just now getting the jist of sockets with .NET. What a trip.... Anyhow.
I have the basic code for a ping. I got a nice jump start from http://www.fawcette.com/vsm/2002_03/...qa/default.asp .
My problem is that the .ReceiveFrom seems to take 100+ milliseconds to complete. While that may not seem like much, it is when you're trying to time the ping. Also, it tends to hang if I try to repeat the ping. I get "Non-blocking socket operation could not be completed immediately".
Any thoughts? The code is below.
Code:Public Sub Echo(ByVal RemoteName As String, ByVal DataSize As Byte, ByVal pStatus As Label) 'for timing Dim intStart As Integer 'for timing Dim intEnd As Integer 'address/port of remote host Dim RemoteHost As IPEndPoint Dim rhEP As EndPoint 'id of this packet Dim Identifier As Short = 0 'sequence number of this packet Dim Sequence As Short = 0 'the socket we use to connect and 'send data through Dim ICMPSocket As Socket 'the request buffer Dim RequestBuffer() As Byte 'the reply buffer Dim ReplyBuffer(255) As Byte 'the number of bytes received Dim RecvSize As Integer = 0 RemoteHost = GetRemoteEndpoint(RemoteName) rhEP = CType(RemoteHost, System.Net.EndPoint) DataSize = Convert.ToByte(DataSize + bufferHeaderSize) ' If odd data size, we need to add ' one empty byte If (DataSize Mod 2 = 1) Then DataSize += Convert.ToByte(1) End If ReDim RequestBuffer(DataSize - 1) ' Set Type Field RequestBuffer(0) = Convert.ToByte(ICMPType.Echo) ' Set ID Field BitConverter.GetBytes(Identifier).CopyTo(RequestBuffer, 4) ' Set Sequence Field BitConverter.GetBytes(Sequence).CopyTo(RequestBuffer, 6) ' load some data into buffer Dim i As Integer For i = 8 To DataSize - 1 RequestBuffer(i) = Convert.ToByte(i Mod 8) Next i ' Set Checksum Call CreateChecksum(RequestBuffer, DataSize, RequestBuffer(2), RequestBuffer(3)) Try ICMPSocket = New Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.Icmp) ICMPSocket.Blocking = False 'Start Count intStart = System.Environment.TickCount 'Send Data ICMPSocket.SendTo(RequestBuffer, 0, DataSize, SocketFlags.None, RemoteHost) 'Receive Data RecvSize = ICMPSocket.ReceiveFrom(ReplyBuffer, SocketFlags.None, rhEP) 'End Count intEnd = System.Environment.TickCount If RecvSize > 0 Then Dim ReS As String Select Case ReplyBuffer(20) Case Convert.ToByte(ICMPType.EchoReply) ReS = (intEnd - intStart).ToString pStatus.Text = "Host: " + RemoteHost.Address.ToString + " - RTT: " + ReS Case Convert.ToByte(ICMPType.Unreachable) ReS = "Unreachable" pStatus.Text = ReS Case Else ReS = "Something Happened" pStatus.Text = ReS End Select End If Catch e As Exception MessageBox.Show(e.Message + vbNewLine + e.TargetSite.Name) Finally If Not ICMPSocket Is Nothing Then ICMPSocket.Close() End If End Try End Sub Public Function GetRemoteEndpoint(ByVal RemoteAddress As String) As IPEndPoint Return New IPEndPoint(Dns.Resolve(RemoteAddress).AddressList(0), portICMP) End Function




Reply With Quote