一般socket UDP编程问题
我有一个 FPGA 设备,我的代码需要与之通信。协议如下:
我发送一个非零字节(UDP)来打开一项功能。然后 FPGA 板开始在我发送的端口上喷出数据。
你看到我的困境了吗?我知道我将消息发送到哪个端口,但我不知道我发送是从哪个端口发送的(是该端口通常不会由操作系统自动选择?)。
我对我应该做的最好的猜测是创建一个带有目标IP和端口号的套接字,然后重用该套接字进行接收。如果我这样做,它是否已经设置为侦听我发送原始消息的端口?
另外,供您参考,此代码的变体将用 Python 和 C# 编写。我可以查找特定的 API,因为它们都遵循 BSD 套接字模型。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这正是
connect(2)
和getsockname(2)
的用途。作为连接 UDP 套接字的一个好处,您不必在每次发送时指定目标地址/端口,您将能够发现不可用的目标端口(来自目标的 ICMP 回复将在下一次发送时显示为错误,而不是丢弃),并且您的操作系统不必在每次发送时隐式连接和断开 UDP 套接字,从而节省一些周期。This is exactly what
connect(2)
andgetsockname(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.您可以将套接字
绑定
到特定端口,请检查man bind
You can
bind
a socket to a specific port, checkman bind
您可以绑定套接字以获得所需的端口。
这样做的唯一问题是您将无法在一台计算机上同时运行多个程序实例。
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.
您正在使用 UDP 发送/接收数据。只需创建一个新的 UDP 套接字并绑定到您所需的接口/端口。然后指示您的 FPGA 程序将 UDP 数据包发送回您绑定的端口。 UDP 不需要您监听/建立连接。 (仅 TCP 需要)
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)