Daily Archives: April 18, 2015

Reading Broadcasted UDP

This is the code used to listen to broadcasted data on the local network.


Private Sub Listen()
Try
DimSTATUS as string = string.empty
Dim port As Integer = 8050
Dim done As Boolean = False
Dim listener As New UdpClient(port)
Dim groupEP As New IPEndPoint(IPAddress.Any, port)
Try
While Not done
STATUS = "Waiting for broadcast"
Dim bytes As Byte() = listener.Receive(groupEP)
STATUS = "Received broadcast from " & groupEP.ToString()
debug.print(Encoding.ASCII.GetString(bytes, 0, bytes.Length))

End While
Catch e As Exception
STATUS = "ERR: 4" & e.Message.ToString
Finally
listener.Close()
End Try
Catch ex As Exception
STATUS = "ERR: " & ex.Message.ToString
End Try

End Sub

Broadcasting UDP

This is useful for broadcasting messages over the local network or to broadcast data coming from hardware over the network where it can be received from another computer and processed.


Imports System.Net
Imports System.Net.Sockets
Imports System.Text

Function GetLocalBroadCastIP() As System.Net.IPAddress
Dim localIP() As System.Net.IPAddress = System.Net.Dns.GetHostAddresses(System.Net.Dns.GetHostName)
For Each current As System.Net.IPAddress In localIP
If current.ToString Like "*[.]*[.]*[.]*" Then
Try
Dim SplitVar() As String = current.ToString.Split(".")
If Len(SplitVar(0)) <= 3 And Len(SplitVar(1)) <= 3 And Len(SplitVar(2)) <= 3 And Len(SplitVar(3)) <= 3 Then current = IPAddress.Parse(SplitVar(0).ToString & "." & SplitVar(1).ToString & "." & SplitVar(2).ToString & ".255") Return current End If Catch ex As Exception End Try End If Next End Function Private Sub SendUdpData(str As String) Dim s As New Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp) Dim broadcast As IPAddress = GetLocalBroadCastIP Dim sendbuf As Byte() = Encoding.ASCII.GetBytes(str) Dim ep As New IPEndPoint(broadcast, 8050) s.SendTo(sendbuf, ep) If txtSent.TextLength > MAXTEXT Then
txtSent.Clear()
End If
txtSent.AppendText(str)
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
SendUDPData("hello World")
end sub