Binding 2 UDP sockets on same port, connected to different destinations, 1 receives

Posted on 16th Feb 2014 by admin

Hello,
My application wants to send/recv data to 2 different UDP ports on a remote computer, using the same source port.
So I bind to the same local port which works, and connect to the remote IP : port which works as well, but then randomly only one of the two sockets will receive data from the stack, even though packets are arriving on the network for both.

In this code, the local UDP port is always 13398; the first time this code is called, the destination is 192.168.13.45:6970 and the second time it's 192.168.13.45:6972.
What would cause only one of the sockets to receive data afterwards? Also it's randomly the first or the second one that receive data, but once both sockets are binded and connected, only that random one will receive data.

Thanks!

SOCKET serverSock = ::socket(AF_INET, SOCK_DGRAM,IPPROTO_UDP);
int i=1;
if ( setsockopt(serverSock, SOL_SOCKET, SO_REUSEADDR, (char *)&i, sizeof(i)) != 0 ) {
logger.warn(_T("Could not set SO_REUSEADDR: %s"), GetWSATextError(WSAGetLastError()));
}

SOCKADDR_IN saServer, dest;
memset(&saServer,0,sizeof(saServer));
saServer.sin_family = AF_INET;
saServer.sin_addr.s_addr = INADDR_ANY; // Since this is a server, any address will do
saServer.sin_port = htons(m_manager->GetLocalUDPPort()); // Convert int to a value for the port field
int ret = bind(serverSock, (struct sockaddr *) &saServer, sizeof(saServer));
if (ret != 0) {
logger.warn(_T("Could not bind to udp port 1: %d, %s"), m_manager->GetLocalUDPPort(), GetWSATextError(WSAGetLastError()));
return false;
}

memset(&dest,0,sizeof(dest));
dest.sin_family=AF_INET;
dest.sin_addr.s_addr=m_deviceIP;
dest.sin_port = htons(m_devicePort1);
ret = connect(serverSock, (sockaddr *) &dest, sizeof(dest));
if (ret != 0) {
logger.warn(_T("Failed to connect to udp 1: %s:%d, %s"), inet_ntoa(dest.sin_addr), m_devicePort1, GetWSATextError(WSAGetLastError()));
return false;
}

Other forums