Question

So I'm building a small little program to send out/receive a UDP broadcast. I realize that UDP is not recommended but I won't know the IP address.

Here is what the client is sending out:

 'Send "Hello Message" to ALL UDPListners

    Public Sub UDPSendHello()

        Dim client As New UDPClient()
        Dim ip As New IPEndPoint(IPAddress.Broadcast, 15000)

        Dim bytes As Byte() = Encoding.ASCII.GetBytes("Hello?")
        client.Send(bytes, bytes.Length, ip)
        client.Close()
    End Sub

For the Server, I get the message "hello" and find the IP address like so:

 'Reciever (Server)

Private ReadOnly udp As New UdpClient(15000)
Public Sub UDPHelloListner()
    udp.BeginReceive(AddressOf Receive, New Object())
End Sub
Private Sub Receive(ByVal ar As IAsyncResult)
    Dim ip As New IPEndPoint(IPAddress.Any, 15000)
    Dim bytes As Byte() = udp.EndReceive(ar, ip)
    Dim message As String = Encoding.ASCII.GetString(bytes)
    If message = "Hello?" Then
        Dim sender As New IPEndPoint(IPAddress.Any, 15000)
        Dim senderRemote As EndPoint = CType(sender, EndPoint)

        My.Settings.clientIPAddress = (ip.AddressFamily.ToString() + ip.Address.ToString)
         MessageBox.Show(My.Settings.clientIPAddress)

       ' ListBox1.Items.Add(My.Settings.clientIPAddress)


    End If

    UDPHelloListner()


End Sub

Now I can use MessageBox.Show(My.Settings.clientIPAddress) to show the IP address of the client who is sending the message. So the above WORKS!

Now if I had 4 instances of this program broadcasting the above as a Client. How could I list each IP of those 4 instances that are running the client? I used ' ListBox1.Items.Add(My.Settings.clientIPAddress) but it says that "The calling thread cannot access this object because a different thread owns it."

Was it helpful?

Solution

If you use WPF try this:

Dispatcher.Invoke(Sub() ListBox1.Items.Add(My.Settings.clientIPAddress))

If you use WinForms:

Invoke(Sub() ListBox1.Items.Add(My.Settings.clientIPAddress))

In both cases I mean that your code is in Window class.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top