1
votes

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. 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:

  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, or each time the port will be chosen for a new message?

  2. 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)

  3. I'm sure there is a known way to handle these situations, what is it?

2

2 Answers

2
votes

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

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? (I need to reserve two ports with the same numbers for UDP and TCP connections)

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.

3) I'm sure there is a known way to handle these situations, what is it?

You've found it. Let the auto-bind happen.

0
votes

I've found some answers on stackoverflow

  1. You can bind to 0 port, that is specified it struct semaddr_in. That will allow you get an unused port for your type of connection. It is not defined to be free for other types of connection.

Look at @remy's answer at Bind to any port available

  1. Yes, they can because headers are specified for UDP or TCP protocols. So the machine can tell one from another.

See Can TCP and UDP sockets use the same port?

  1. If you bind to 0 port you'll get ability to listen to it before calling sendto