Nate
Nate

Reputation: 5407

General sockets UDP programming question

I have an FPGA device with which my code needs to talk. The protocol is as follows:

I send a single non-zero byte (UDP) to turn on a feature. The FPGA board then begins spewing data on the port from which I sent.

Do you see my dilemma? I know which port I sent the message to, but I do not know from which port I sent (is this port not typically chosen automatically by the OS?).

My best guess for what I'm supposed to do is create a socket with the destination IP and port number and then reuse the socket for receiving. If I do so, will it already be set up to listen on the port from which I sent the original message?

Also, for your information, variations of this code will be written in Python and C#. I can look up specific API's as both follow the BSD socket model.

Upvotes: 0

Views: 919

Answers (4)

Nikolai Fetissov
Nikolai Fetissov

Reputation: 84159

This is exactly what connect(2) and getsockname(2) are for. As a bonus for connecting the UDP socket you will not have to specify the destination address/port on each send, you will be able to discover unavailable destination port (the ICMP reply from the target will manifest as error on the next send instead of being dropped), and your OS will not have to implicitly connect and disconnect the UDP socket on each send saving some cycles.

Upvotes: 2

futureelite7
futureelite7

Reputation: 11502

You're using UDP to send/receive data. Simply create a new UDP socket and bind to your desired interface / port. Then instruct your FPGA program to send UDP packets back to the port you bound to. UDP does not require you to listen/set up connections. (only required with TCP)

Upvotes: 0

Elalfer
Elalfer

Reputation: 5338

You can bind a socket to a specific port, check man bind

Upvotes: 1

RageZ
RageZ

Reputation: 27313

you can bind the socket to get the desired port.

The only problem with doing that is that you won't be able to run more then one instance of your program at a time on a computer.

Upvotes: 0

Related Questions