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