Finding out UDP Broadcast source IP with SDL_Net
I'开发者_如何学Cm implementing a very basic sort of "server discovery": once in a while my server (lets say at 192.168.0.4) broadcasts a very simple UDP packet to 255.255.255.255:1234
Then my clients, wherever they are, listen on 1234 for incoming packets. The packets arrive fine, but I'm unable to get who requested the broadcast (192.168.0.4). The only IP I received as the "sender" is 192.168.0.1, the router. I think this makes sense, but its useless since what I really need is the server's IP; the one who started the broadcast.
As a side note, I cannot store the servers IP on the broadcast packet since I really don't know what IP the servers uses to reach some client on some network (could be any local net on any interface) and after all, there is no portable way of knowing interfaces and IPs assigned to them.
Source code is pretty simple:
/* packet */
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;
/* omitting the while/sleep loop here =) */
if (SDLNet_UDP_Recv(sock, packet))
{
memcpy (&data, packet->data, sizeof(my_packet_struct));
}
/* here I'm getting 192.168.0.1 as the source :( */
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);
The PCap library could do this for sure, the only problem residing in the fact that the end user would need PCap installed (unless you're willing to create a standalone version). If you really need to avoid extra additions like this, you could also just write separate cases for each target platform. I know it's messy, but sometimes it's inescapable.
Best of luck.
Just include the server address in the packet that you're broadcasting, perhaps with some sort of hash just to make sure it's not some other server using the same port.
精彩评论