[英]Sendto from unbinded UDP socket
situation: I need to broadcast from client using UDP from some free port, then to accept tcp connection on client from server on the port with the same number, but TCP.情况:我需要从某个空闲端口使用UDP从客户端进行广播,然后从具有相同编号但TCP的端口上的服务器接受客户端上的tcp连接。 That's why I need to listen (and bind) to this port BEFORE broadcasting.
这就是为什么我需要在广播之前监听(并绑定)到这个端口。 The port cannot be const, because I can have multiple clients running on one machine.
端口不能是常量,因为我可以在一台机器上运行多个客户端。 So here some questions, which can help me to make this situation clearer:
所以这里有一些问题,可以帮助我更清楚地说明这种情况:
If I made sendto from unbinded UDP socket, is it binded to any free port and all next sendto messages will go from this port, or each time the port will be chosen for a new message?如果我从未绑定的 UDP 套接字进行发送,它是否绑定到任何空闲端口并且所有下一个发送消息都将从该端口发送,或者每次都会为新消息选择该端口?
Can I ask system to reserve some free port for me?我可以要求系统为我保留一些空闲端口吗? (I need to reserve two ports with the same numbers for UDP and TCP connections)
(我需要为 UDP 和 TCP 连接保留两个具有相同编号的端口)
I'm sure there is a known way to handle these situations, what is it?我确定有一种已知的方法来处理这些情况,它是什么?
1)If I made sendto from unbinded UDP socket, is it binded to any free port and all next sendto messages will go from this port
1)如果我从未绑定的UDP套接字发送sendto,它是否绑定到任何空闲端口并且所有下一个sendto消息都将从该端口发送
Yes.是的。
or each time the port will be chosen for a new message?
或者每次都会为新消息选择端口?
No.不。
2) Can I ask system to reserve some free port for me?
2) 我可以要求系统为我预留一些空闲端口吗? (I need to reserve two ports with the same numbers for UDP and TCP connections)
(我需要为 UDP 和 TCP 连接保留两个具有相同编号的端口)
That's what happens when the auto-bind occurs.这就是自动绑定发生时发生的情况。 You can do explicitly by binding to port number zero, but it isn't necessary.
您可以通过绑定到端口号零来显式执行此操作,但这不是必需的。 It also does not guarantee that you can bind both UDP and TCP to the same port number.
它也不保证您可以将 UDP 和 TCP 绑定到相同的端口号。
3) I'm sure there is a known way to handle these situations, what is it?
3)我确定有一种已知的方法来处理这些情况,它是什么?
You've found it.你已经找到了。 Let the auto-bind happen.
让自动绑定发生。
I've found some answers on stackoverflow我在 stackoverflow 上找到了一些答案
0
port, that is specified it struct semaddr_in
.0
端口,即指定它struct semaddr_in
。 That will allow you get an unused port for your type of connection. Look at @remy's answer at Bind to any port available在绑定到任何可用端口时查看@remy 的回答
See Can TCP and UDP sockets use the same port?请参阅TCP 和 UDP 套接字是否可以使用相同的端口?
listen
to it before calling sendto
sendto
之前listen
它
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.