To send and receive UDP messages (communication with PLC) I need to set (or at least know) the output port of the UDP packet. The controller responds to the same port from which the message came.
How do I set or read the output port of sent UDP message.
You can optionally choose the port you want to use, by explicitly
bind()'ing the socket to a specific port number before you
sendto() or
recvfrom() any packets with that socket. Or, you can
bind() the socket to port 0 to let the OS choose an available ephemeral port for you, and then you can query the socket with
getsockname() to find out which port number the OS had chosen.
However, if you are the first party to send anything, you don't really need to explicitly
bind() the socket beforehand, just let the OS bind it for you during the 1st
sendto() call, and then subsequent
recvfrom() calls will receive on that same port.