unix上的UDP套接字问题 - bind:已经在使用的地址

Fab*_*son 6 c++ sockets linux boost udp

首先,我知道在同一个主题上还有其他几个主题,但是我无法在那些可以帮助我的内容中找到任何内容,所以我会尝试对我的情况非常具体.

我已经设置了一个简单的UDP客户端/ UDP服务器对,负责在几个并行模拟之间发送数据.也就是说,模拟器的每个实例都在一个单独的线程中运行,并在UDP套接字上发送数据.在主线程中,服务器正在运行,并在模拟之间路由消息.

(对于这个问题)服务器代码的重要部分如下所示:

UDPServer::UDPServer(boost::asio::io_service &m_io_service) :
   m_socket(m_io_service, udp::endpoint(udp::v4(), PORT_NUMBER)),
   m_endpoint(boost::asio::ip::address::from_string("127.0.0.1"), PORT_NUMBER)
{
   this->start_receive();
};

void UDPServer::start_receive() {

   // Set SO_REUSABLE to true
   boost::asio::socket_base::reuse_address option(true);
   this->m_socket.set_option(option);

   // Specify what happens when a message is received (it should call the handle_receive function)
   this->m_socket.async_receive_from(   boost::asio::buffer(this->recv_buffer),
                                        this->m_endpoint,
                                        boost::bind(&UDPServer::handle_receive, this, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred));

};
Run Code Online (Sandbox Code Playgroud)

这在我的Windows工作站上工作正常.

事情是; 我希望能够在Linux集群上运行它,这就是我编译它并尝试在集群节点上运行它的原因.代码编译顺利,但当我尝试运行它时,我得到错误

bind: address already in use
Run Code Online (Sandbox Code Playgroud)

我使用1024以上的端口号,并验证它没有被其他程序使用.如上所示,我也设置了reuse_address选项,所以我真的不知道还有什么可能是错的.

eca*_*mur 4

便携使用,SO_REUSEADDR您需要在将套接字绑定到通配符地址之前设置该选项:

UDPServer::UDPServer(boost::asio::io_service &m_io_service) :
   m_socket(m_io_service, udp::v4()),
   m_endpoint()
{
   boost::asio::socket_base::reuse_address option(true);
   this->m_socket.set_option(option);
   this->m_socket.bind(udp::endpoint(udp::v4(), PORT_NUMBER));
   this->start_receive();
}
Run Code Online (Sandbox Code Playgroud)

在您的原始代码中,采用构造函数的构造函数endpoint在一行中打开并绑定套接字 - 它很简洁,但不太灵活。在这里,我们在构造函数调用中构造并打开套接字,然后在设置选项后绑定它。

顺便说一句,m_endpoint如果您只是将其用作无论如何的输出参数,那么初始化就没有多大意义async_receive_from