I have the following code:
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";
}
When I CLOSE the server, with close(), of couse, I can't open the server again in the same port. Why? I need to change the port OR reboot the system. It happens only in Ubuntu AND MacOSX. In Windows I don't have this problem.
The error happend in the ::bind() function. It doesn't allow me to re-bind() a socket twice.
How do I re-bind?