开发者

Reusing a port number in a UDP

In ASIO, s it possible to create another socket that has the same source port as another socket?

My UDP server application is calling receive_from using port 3000. It passes the packet off to a worker thread which will send the response (currently using a dynamic source port).

The socket in the other thread is created like this:

udp::socket sock2(io_service, udp::endpoint(udp::v4(), 0));

And responds to the original request using the sender_endpoint saved with the original packet.

What I'd like to be able to do is respond to the client using the same source port as the server is listening on. But I can't see how that can be done. I get an exception if I try that saying address in use. Is it possible to do what I'm asking? The reason I want that is if I use dynamic ports, it m开发者_StackOverflow中文版eans the clients need to add special firewall rules in windows to allow the reply packets to be read. I've found that if the source port is the same in the reply, windows firewall will allow it to pass back in.


The exception tells you as it is: you can't create two live sockets with the same source port. I don't know ASIO, but you should be able to create the socket before spinning off the thread, keeping reference to the socket and the thread for later use, and once the data sending thread is idle, joining back to it and sending any other stuff.

EDIT: with a little bit of effort, you can also make a socket for which you don't have to wait until the entire data from one thread has been sent: have a worker thread owning the socket listen on a queue for chunks of data (ideally exactly the size of the payload you intend to send) and send arbitrary chunks of payload to this queue, from multiple threads.


You should be able to use the SO_REUSEADDR socket option to bind multiple sockets to the same address. But having said that, you don't want to do this because it's not specified which socket will receive incoming data on that port (you would have to check all sockets for incoming data)

The better option is just to use the same socket to send replies - this can safely be done from multiple threads without any additional synchronisation (as you are using UDP).


send reply to the same socket (that you received client's request on) instead of creating new one but make sure you don't send to the same socket from both threads simultaneously

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜