Question

I have a WinForm application made it in VB.NET and I need to answer in the same port that I receive the UDP message but with the code that I have running the application source port is being chosen by the O.S., or it seems that.

Private Sub UdpSend(ByVal txtMessage As String)
    Dim pRet As Integer
    GLOIP = IPAddress.Parse(IpRemotaLbl.Text)
    GLOINTPORT = RemotePortLbl.Text
    MyUdpClient.Connect(GLOIP, GLOINTPORT)
    bytCommand = Encoding.ASCII.GetBytes(txtMessage)
    pRet = MyUdpClient.Send(bytCommand, bytCommand.Length)
    'Console.WriteLine("No of bytes send " & pRet)
    PrintLog("No of bytes send " & pRet)
End Sub

In example, if I receive the UDP message on port 8082 the answer, currently, is being sent from port 1515(local) to 8082(remote) and I need to send the message from port 8082(local) to 8082(remote).

Thanks.

Was it helpful?

Solution

You need to bind the UdpClient to a local port before you call Send(). The only way to specify the source port is in the UdpClient's constructor, so if you do not know which source port to use until you have received a message first then you will have to wait until then before creating the UdpClient.

Private Sub UdpSend(ByVal txtMessage As String)
    Dim pRet As Integer
    Dim MyUdpClient as UdpClient = new UdpClient(8082); ' <-- here
    MyUdpClient.Connect(IPAddress.Parse(IpRemotaLbl.Text), RemotePortLbl.Text)
    bytCommand = Encoding.ASCII.GetBytes(txtMessage)
    pRet = MyUdpClient.Send(bytCommand, bytCommand.Length)
    'Console.WriteLine("No of bytes send " & pRet)
    PrintLog("No of bytes send " & pRet)
End Sub
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top