كيف يمكنني إعادة ربط مقبس في MacOSX/Ubuntu؟ مرة ثانية
-
25-09-2019 - |
سؤال
لدي الرمز التالي:
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 () ، من couse ، لا يمكنني فتح الخادم مرة أخرى في نفس المنفذ. لماذا ا؟ أحتاج إلى تغيير المنفذ أو إعادة تشغيل النظام. يحدث ذلك فقط في Ubuntu و Macosx. في Windows ليس لدي هذه المشكلة.
خطأ يحدث في وظيفة :: 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.
لا تنتمي إلى StackOverflow