I have been facing a problem with UDP socket programming. I have to reuse port number for two different IP address. I am actually using SO_REUSEADD. I have no problem with debug version but with release version the bind is failing for 2nd IP address with the error code 10048. It's the error code for WSAEADDRINUSE. I am trying to with WinXP machine using Visual C++ 6.0.
The application which we are using needs to connect to Primary and Backup server. The UDP connection should be established with both Primary and Backup server so that if the Primary server goes down, the client can still communicate with backup server and retrieves all information.
I can’t use different port for both Primary and Backup serer as we are allowing multiple clients on a PC. Also we are not handling this on the server side since it’s a redundant system.
Primary Server (Listening Port : 6000)
Backup Server (Listen on 6000)
Client1 (Listening Port 6003: Local Port: 6002 so that the server knows it should send it to 6003, just add one and send the response back)
Client2 (Listening Port 6005: Local Port: 6002 so that the server knows it should send it to 6003, just add one and send the response back)
I have a mechanism to select both listening and local port on the client. I bind with the specific portnumber and close the socket after identifying the port numbers.
The setsockopt is successful for SO_REUSEADDR but bind fails for backup server. It’s strange that this issue never happens in debug version but release version fails to bind for the backup server.
Here is the code to handle this scenario.
WSADATA WsaData;
int err = WSAStartup(MAKEWORD(1,1), &WsaData);
if ( err != 0 )
{
return (kOpenInvalidDev);
}
if ((mSocket = socket(PF_INET, SOCK_DGRAM, 0)) == INVALID_SOCKET)
{
return (kOpenDevError);
}
int optval;
if(!mIsServer)
{
if (setsockopt(mSocket, SOL_SOCKET, SO_REUSEADDR, (char *) &optval,
sizeof (optval)) == SOCKET_ERROR)
{
close(); // close.
return (kOpenDevError);
}
}
if (setsockopt(mSocket, SOL_SOCKET, SO_BROADCAST, (char *) &optval,
sizeof (optval)) == SOCKET_ERROR)
{
close(); // close.
return (kOpenDevError);
}
else if (mLocalAddr.sin_port != 0)
{
if (bind(mSocket, (struct sockaddr*)&mLocalAddr, sizeof(mLocalAddr)) ==
SOCKET_ERROR)
{
return (kOpenDevBusy);
}
}
}