From 1d4a7df6b5ea42c8d75b9fe907d1d4ad7baab906 Mon Sep 17 00:00:00 2001 From: Volker Fischer Date: Thu, 7 Apr 2011 18:26:54 +0000 Subject: [PATCH] give more flexibility with the client port numbers --- src/main.cpp | 2 +- src/socket.cpp | 21 ++++++++++++++++----- src/socket.h | 7 ++++++- 3 files changed, 23 insertions(+), 7 deletions(-) diff --git a/src/main.cpp b/src/main.cpp index e24f5157..fa9c7f4e 100755 --- a/src/main.cpp +++ b/src/main.cpp @@ -259,7 +259,7 @@ int main ( int argc, char** argv ) if ( !bIsClient && !strCentralServer.isEmpty() ) { bIsCentralServer = - ( !strCentralServer.compare ( "localhost" ) || + ( !strCentralServer.toLower().compare ( "localhost" ) || !strCentralServer.compare ( "127.0.0.1" ) ); } diff --git a/src/socket.cpp b/src/socket.cpp index 3d7c8eb1..a1784235 100755 --- a/src/socket.cpp +++ b/src/socket.cpp @@ -32,14 +32,25 @@ void CSocket::Init ( const quint16 iPortNumber ) // allocate memory for network receive and send buffer in samples vecbyRecBuf.Init ( MAX_SIZE_BYTES_NETW_BUF ); - // initialize the listening socket, per definition use the port number plus - // one for the client to make it possible to run server and client on the - // same computer + // initialize the listening socket bool bSuccess; if ( bIsClient ) { - bSuccess = SocketDevice.bind ( - QHostAddress( QHostAddress::Any ), iPortNumber + 1 ); + // Per definition use the port number plus one 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 = 1; // start value: port nubmer plus one + bSuccess = false; // initialization for while loop + while ( !bSuccess && + ( iClientPortIncrement <= NUM_SOCKET_PORTS_TO_TRY ) ) + { + bSuccess = SocketDevice.bind ( + QHostAddress( QHostAddress::Any ), + iPortNumber + iClientPortIncrement ); + + iClientPortIncrement++; + } } else { diff --git a/src/socket.h b/src/socket.h index 59780368..42d89c93 100755 --- a/src/socket.h +++ b/src/socket.h @@ -42,6 +42,11 @@ class CServer; // forward declaration of CServer +/* Definitions ****************************************************************/ +// number of ports we try to bind until we give up +#define NUM_SOCKET_PORTS_TO_TRY 50 + + /* Classes ********************************************************************/ class CSocket : public QObject { @@ -59,7 +64,7 @@ public: : pServer ( pNServP ), bIsClient ( false ) { Init ( iPortNumber ); } void SendPacket ( const CVector& vecbySendBuf, - const CHostAddress& HostAddr ); + const CHostAddress& HostAddr ); protected: void Init ( const quint16 iPortNumber = LLCON_DEFAULT_PORT_NUMBER );