As part of a simple networking project I’m trying to connect two computers together to send a simple data packet. The client uses a broadcast to find servers, and my server successfully detects this broadcast from the client.
The server then sends a reply packet, however I am unable to get the client to listen to the packet.
The problem seems to lie with the broadcasting method, since if I use a direct server connection, aka instead of INADDR_BROADCAST I specify the IP address 127.0.0.1 or 192.168.0.x then the server connects, sends a reply, and the client receives it.
The listening code in the client:
// Stop the client from waiting for packets if there are none.
fd_set checksockets;
checksockets.fd_count = 1;
checksockets.fd_array[0]=m_listenSocket;
struct timeval t;
t.tv_sec=0;
t.tv_usec=0;
int waiting = select(NULL, &checksockets, NULL, NULL, &t);
// If there is at least one packet receive it.
if(waiting>0) {
std::cout << "Packet received.\n";
}
From this point I attempt to find the server address with the recvfrom() method.
I’ve made sure to use the broadcast flag on the client socket, right after creating it. This returns no errors.
int value=true;
int result = setsockopt(m_socket, SOL_SOCKET, SO_BROADCAST, (char*)&value, sizeof( value ) );
I’ve checked all possible WINSOCK functions that I’ve used and none return any errors.
I’ve also tried creating a second socket only for listening on the same port, but this conflicts with the server and therefore fails to open.
So essentially, what I’m trying to ask: How can I have a client listen for a reply from a broadcast? – aka the server address is unknown at first, I’m attempting to create a new socket using the reply address, however I’m not getting a reply address from a broadcast, despite the server receiving the broadcast and definitely sending a reply.
As you point out you won’t receive any back when bound to
INADDR_BROADCAST. This is normal: when you are bound to an address you only receive packets from that address. You don’t need to bind the sockets to any address at all. This operation is usually required for connected sockets (i.e. TCP). If the receiving socket works I guess it is because you’re doing all your tests on the same machine.If you want to receive packets from a given address you can try to use
connectorsendtoandreceivefrom.