gpt4 book ai didi

linux - 如何在 MacOS/Ubuntu 中重新绑定(bind)套接字?第二次

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:02:22 29 4
gpt4 key购买 nike

我有以下代码:

if ( ( m_mainSocket = ::socket( PF_INET, SOCK_STREAM, IPPROTO_TCP ) ) < 0 )
{
throw Exception( __FILE__, __LINE__ ) << "Unable to create socket";
}

int on( 0 );

if ( setsockopt( m_mainSocket, SOL_SOCKET, SO_REUSEADDR, &on, sizeof( on ) ) )
{
throw Exception( __FILE__, __LINE__ ) << "Can't make server socket resusable.";
}

sockaddr_in addr;
memset( &addr, 0, sizeof( addr ) );

addr.sin_family = AF_INET;
addr.sin_addr.s_addr = htonl( INADDR_ANY );
addr.sin_port = htons( p_localPort );

if ( ::bind( m_mainSocket, reinterpret_cast< sockaddr * >( &addr ), sizeof( addr ) ) < 0 )
{
throw Exception( __FILE__, __LINE__ ) << "Failed to bind the server socket";
}

当我使用 close() 关闭服务器时,我当然无法在同一端口再次打开服务器。为什么?我需要更改端口或重新启动系统。它只发生在 Ubuntu 和 MacOSX 中。在 Windows 中我没有这个问题。

错误发生在::bind() 函数中。它不允许我重新绑定(bind) () 一个套接字两次。

如何重新绑定(bind)?

最佳答案

您需要将 1 而不是 0 传递给 REUSEADDR。

来自 socket(7) 手册页:

   Socket Options       These socket options can be set by using setsockopt(2)  and  read  with       getsockopt(2) with the socket level set to SOL_SOCKET for all sockets:      ....       SO_REUSEADDR              Indicates  that  the rules used in validating addresses supplied              in a bind(2) call should allow reuse of  local  addresses.   For              AF_INET  sockets  this means that a socket may bind, except when              there is an active listening socket bound to the address.   When              the listening socket is bound to INADDR_ANY with a specific port              then it is not possible to bind  to  this  port  for  any  local              address.  Argument is an integer boolean flag.

关于linux - 如何在 MacOS/Ubuntu 中重新绑定(bind)套接字?第二次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2186870/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com