I implement a very simple “server discovery”: from time to time my server (say 192.168.0.4) broadcasts a very simple UDP packet up to 255.255.255.255:1234
Then my clients, wherever they are, listen to 1234 for incoming packets. Packets arrive normally, but I can’t get who requested the broadcast (192.168.0.4). The only IP that I received as the “sender” is 192.168.0.1, a router. I think this makes sense, but is useless, as I really need the server IP address; the one who started the broadcast.
As a side note, I can’t store the IP addresses of the servers in the broadcast packet, since I really don’t know which IP server uses the servers to access some client on any network (there can be any local network on any interface) and after all, there is no portable way to know the interfaces and IP addresses assigned to them.
The source code is pretty simple:
struct my_packet_struct { int a,b,c };
Client
UDPpacket* packet = SDLNet_AllocPacket (sizeof(my_packet_struct));
UDPsocket sock = SDLNet_UDP_Open (1234);
my_packet_struct data;
if (SDLNet_UDP_Recv(sock, packet))
{
memcpy (&data, packet->data, sizeof(my_packet_struct));
}
uint32_t ip = SDLNet_Read32 (&packet->address.host);
Server
UDPpacket* packet = SDLNet_AllocPacket (sizeof(my_packet_struct));
UDPsocket sock = SDLNet_UDP_Open (0);
my_packet_struct data;
IPaddress addr;
SDLNet_ResolveHost (&addr, "255.255.255.255", 1234);
packet->address.host = addr.host;
packet->address.port = addr.port;
packet->len = sizeof(data);
memcpy (packet->data, &data, sizeof(data));
SDLNet_UDP_Send (sock, -1, packet);