tags:

views:

275

answers:

4

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.

A: 

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.

RageZ
Well, you can always bind to another port. What's important is that you keep track of what port you're actually binding to.
futureelite7
@futurelite7: yeah my remark if was using a defined port. like always the same.
RageZ
+1  A: 

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

Elalfer
A: 

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)

futureelite7
+2  A: 

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.

Nikolai N Fetissov
This is right. You don't need to `bind()` - the random port that OS gave you will be fine (and no, you don't have to do anything special to allow that UDP socket to listen for incoming packets). `connect`ing it is a good idea, though.
caf