I've been trying, without success, to get one machine to send a UDP
broadcast and another machine on the network to read it. I can get the
two machines to talk to each other via UDP when one is sending messages
directly to the other (not broadcasting). I can also see the packets on
the receiver machine using snoop.
I would have thought something similar to the following would have
worked..
Broadcaster:
char buffer[80];
int send_size, optval = 1;
union sock
{
struct sockaddr s;
struct sockaddr_in i;
sd = socket (AF_INET, SOCK_DGRAM, 0);Quote:} remote_addr;
setsockopt (sd, SOL_SOCKET, SO_BROADCAST, (const void *) &optval,
sizeof(optval));
remote_addr.i.sin_family = AF_INET;
remote_addr.i.sin_port = htons (PORT_NUMER);
remote_addr.i.sin_addr.s_addr = inet_addr ("###.###.###.255");
/* While you don't have to call connect for UDP, doing so allows you */
/* to send packets without specifying the IP address with each send. */
connect (sd, &remote_addr.s, sizeof(struct sockaddr));
send_size = sprintf (buffer, "Whatever");
send (sd, buffer, send_size, 0);
Receiver
sd = socket (AF_INET, SOCK_DGRAM, 0);
local_addr.i.sin_family = AF_INET;
local_addr.i.sin_port = htons (PORT_NUMBER);
local_addr.i.sin_addr.s_addr = htonl (INADDR_BROADCAST);
bind (sd, &local_addr.s, sizeof (struct sockaddr));
remote_addr.i.sin_family = AF_INET;
remote_addr.i.sin_port = htons (PORT_NUMER);
remote_addr.i.sin_addr.s_addr = inet_addr (BROADCASTERS_IP_ADDR);
connect (sd, &remote_addr.s, sizeof(struct sockaddr));
recv (sd, buffer, size, 0);
Any ideas why this doesn't work? Can anyone provide source that does
work?