重用UDP中的端口号 [英] Reusing a port number in a UDP

查看:330
本文介绍了重用UDP中的端口号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在ASIO中,是否可以创建另一个具有与另一个套接字相同的源端口的套接字?

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

我的UDP服务器应用程序正在使用端口3000调用receive_from.它传递数据包 关闭到将发送响应的工作线程(当前使用动态源端口).

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));

并使用与原始数据包一起保存的sender_endpoint响应原始请求.

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

我想做的是使用与服务器侦听相同的源端口响应客户端.但是我看不到该怎么做.如果尝试使用说出的地址,我会得到一个例外.可以按照我的要求去做吗?我想要的原因是如果我使用动态端口,这意味着客户端需要在Windows中添加特殊的防火墙规则以允许读取回复数据包.我发现,如果回复中的源端口相同,则Windows防火墙将允许其回传.

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

推荐答案

您应该能够使用SO_REUSEADDR套接字选项将多个套接字绑定到同一地址.但话虽如此,您不想这样做,因为未指定哪个套接字将在该端口上接收传入数据(您必须检查所有套接字中的传入数据)

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)

更好的选择是仅使用同一套接字发送答复-可以安全地从多个线程完成此操作,而无需任何其他同步(就像使用UDP一样).

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

这篇关于重用UDP中的端口号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆