Allow client to bind on a random port
This commit is contained in:
parent
bba56fc988
commit
4efe081084
1 changed files with 25 additions and 13 deletions
|
@ -54,23 +54,35 @@ void CSocket::Init ( const quint16 iPortNumber )
|
||||||
|
|
||||||
if ( bIsClient )
|
if ( bIsClient )
|
||||||
{
|
{
|
||||||
// Per definition use the port number plus ten for the client to make
|
if (iPortNumber == 0)
|
||||||
// it possible to run server and client on the same computer. If the
|
|
||||||
// port is not available, try "NUM_SOCKET_PORTS_TO_TRY" times with
|
|
||||||
// incremented port numbers
|
|
||||||
quint16 iClientPortIncrement = 10; // start value: port nubmer plus ten
|
|
||||||
bSuccess = false; // initialization for while loop
|
|
||||||
|
|
||||||
while ( !bSuccess &&
|
|
||||||
( iClientPortIncrement <= NUM_SOCKET_PORTS_TO_TRY ) )
|
|
||||||
{
|
{
|
||||||
UdpSocketInAddr.sin_port = htons ( iPortNumber + iClientPortIncrement );
|
// If port number is 0, bind the client to a random available port.
|
||||||
|
UdpSocketInAddr.sin_port = htons ( iPortNumber );
|
||||||
|
|
||||||
bSuccess = ( ::bind ( UdpSocket ,
|
bSuccess = ( ::bind ( UdpSocket ,
|
||||||
(sockaddr*) &UdpSocketInAddr,
|
(sockaddr*) &UdpSocketInAddr,
|
||||||
sizeof ( sockaddr_in ) ) == 0 );
|
sizeof ( sockaddr_in ) ) == 0 );
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
// Per definition use the port number plus ten for the client to make
|
||||||
|
// it possible to run server and client on the same computer. If the
|
||||||
|
// port is not available, try "NUM_SOCKET_PORTS_TO_TRY" times with
|
||||||
|
// incremented port numbers
|
||||||
|
quint16 iClientPortIncrement = 10; // start value: port nubmer plus ten
|
||||||
|
bSuccess = false; // initialization for while loop
|
||||||
|
|
||||||
iClientPortIncrement++;
|
while ( !bSuccess &&
|
||||||
|
( iClientPortIncrement <= NUM_SOCKET_PORTS_TO_TRY ) )
|
||||||
|
{
|
||||||
|
UdpSocketInAddr.sin_port = htons ( iPortNumber + iClientPortIncrement );
|
||||||
|
|
||||||
|
bSuccess = ( ::bind ( UdpSocket ,
|
||||||
|
(sockaddr*) &UdpSocketInAddr,
|
||||||
|
sizeof ( sockaddr_in ) ) == 0 );
|
||||||
|
|
||||||
|
iClientPortIncrement++;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
|
|
Loading…
Reference in a new issue