简体   繁体   English

连接一个 UDP 套接字,但仍然接收来自其他来源的数据报

[英]Connect a UDP socket, but still receive datagrams from other sources

Is it possible to set the default destination of a UDP socket just like connect does, but without loosing the ability to receive datagrams from other sources?是否可以像connect一样设置 UDP 套接字的默认目标,但不会失去从其他来源接收数据报的能力?

I'm talking about the native OS socket API (BSD-socket / winsock2) and I'm interested in answers for both linux and windows platforms.我说的是本机操作系统套接字 API(BSD-socket / winsock2),我对 linux 和 windows 平台的答案感兴趣。

[ EDIT :] [编辑:]
In case this is unclear, here is the problematic part from the connect docs :如果不清楚,这是连接文档中的问题部分:

If the socket sockfd is of type SOCK_DGRAM then addr is the address to which datagrams are sent by default, and the only address from which datagrams are received.如果套接字 sockfd 是 SOCK_DGRAM 类型,那么 addr 是默认发送数据报的地址,也是接收数据报的唯一地址。

Is it possible to set the default destination of a UDP socket just like connect does, but without loosing the ability to receive packages from other sources?是否可以像 connect 一样设置 UDP 套接字的默认目标,但不会失去从其他来源接收包的能力?

As far as I can tell, it is not -- connect() on a UDP socket both sets a default-send-destination and installs a filter so that incoming UDP packets from all other destinations than the specified address/port are dropped.据我所知,它不是 - UDP 套接字上的connect()既设置了默认发送目标安装了过滤器,以便从除指定地址/端口之外的所有其他目标传入的 UDP 数据包被丢弃。

My solution to the problem was to just call sendto() and recvfrom() instead (if you have a UDPSocket class or similar in your codebase, you can cache the default-send address as a private member variable in that class, so that the rest of your codebase can just call a Send() method, and leave it to that method to handle the sendto() arguments)我对该问题的解决方案是只调用sendto()recvfrom() (如果您的代码库中有UDPSocket class 或类似的,您可以将默认发送地址缓存为该 class 中的私有成员变量,以便您的代码库的 rest 可以只调用Send()方法,并将其留给该方法来处理sendto()参数)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM