views:

284

answers:

5
+2  Q: 

Broadcasting

Could anyone please provide me with the code or link to send and receive broadcast messages if possible using UDP?

I have been stuck in a problem and hope if u guys could help me resolve it. Thanks

A: 

UDP Multicast in Java

CookieOfFortune
Can I point out that multicast is distinct from broadcast? For multicast you have group membership and selective routing, whereas broadcast is indiscriminate.
Brian Agnew
+1  A: 

Here's a C# example:

using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;

class MainClass {
    static void Main(string[] args)
    {
        ThreadPool.QueueUserWorkItem(StartUDPListener);

        UdpClient udpClient = new UdpClient();
        udpClient.Send(new byte[]{0x00}, 1, new IPEndPoint(IPAddress.Broadcast, 4567));

        Console.ReadLine();
   }

   private static void StartUDPListener(object state) {
       UdpClient udpServer = new UdpClient(new IPEndPoint(IPAddress.Broadcast, 4567));

       IPEndPoint remoteEndPoint = null;
       udpServer.Receive(ref remoteEndPoint);

       Console.WriteLine("UDP broadcast received from " + remoteEndPoint + ".");   
   }
}
sipwiz
A: 

I'm not going to post code, just a couple of observations:

  1. Sending a UDP broadcast is just like sending a unicast packet - only the destination address is different. This can be INADDR_BROADCAST (255.255.255.255) but that can cause problems on systems with multiple network interfaces. It's better to send to the specific broadcast address for the interface that you want to send on. The only significant caveat is that you may need to set the SO_BROADCAST socket option before your O/S will permit sending the broadcast.

  2. Receiving a UDP broadcast is exactly like receiving a unicast packet. No special code is necessary, but you should have the receiver bound to INADDR_ANY.

Alnitak
Almost true on both points. On point 1: you must set the `SO_BROADCAST` socket option in order to send broadcast packets.On point 2: The receiver has to bind either to any interface ( `INADDR_ANY` ) or to the network's broadcast address ( either the all networks one or the directed one ). If it binds to a unicast address it won't get broadcast packets.
Robert S. Barnes
@Robert - good points, although not every O/S seems to require SO_BROADCAST. MacOS X doesn't AFAIK.
Alnitak
A: 

Here is example code for both the broadcast sender and receiver.

It should be easily portable to any language which has access to the standard Berkly Sockets API.

#!/usr/bin/perl -w
# broadcast sender script
use strict;
use diagnostics;
use Socket;

my $sock;
my $receiverPort = 9722;
my $senderPort = 9721;

socket($sock, PF_INET, SOCK_DGRAM, getprotobyname('udp'))   || die "socket: $!";
setsockopt($sock, SOL_SOCKET, SO_REUSEADDR, pack("l", 1))   || die "setsockopt: $!";
setsockopt($sock, SOL_SOCKET, SO_BROADCAST, pack("l", 1)) or die "sockopt: $!";
bind($sock, sockaddr_in($senderPort, inet_aton('192.168.2.103')))  || die "bind: $!";

while (1) {
    my $datastring = `date`;
    my $bytes = send($sock, $datastring, 0, 
                     sockaddr_in($receiverPort, inet_aton('192.168.2.255')));
    if (!defined($bytes)) { 
        print("$!\n"); 
    } else { 
        print("sent $bytes bytes\n"); 
    }
    sleep(2);
}

#!/usr/bin/perl -w
# broadcast receiver script
use strict;
use diagnostics;
use Socket;

my $sock;

socket($sock, PF_INET, SOCK_DGRAM, getprotobyname('udp'))   || die "socket: $!";
setsockopt($sock, SOL_SOCKET, SO_REUSEADDR, pack("l", 1))   || die "setsockopt: $!";
bind($sock, sockaddr_in(9722, inet_aton('192.168.2.255')))  || die "bind: $!"; 

# just loop forever listening for packets
while (1) {
    my $datastring = '';
    my $hispaddr = recv($sock, $datastring, 64, 0); # blocking recv
    if (!defined($hispaddr)) {
        print("recv failed: $!\n");
        next;
    }
    print "$datastring";
}
Robert S. Barnes
A: 

I'm just starting to learn this, but this was my first working example, it might help you.

Receiver code:

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;

class UDPReceiver
{
    static void Main(string[] args)
    {
        IPEndPoint endPoint;
        using (UdpClient client = new UdpClient(9998))
        {
            bool connected = true;
            while (connected)
            {
                byte[] dataBytes = client.Receive(ref endPoint);
                string dataString = Encoding.UTF8.GetString(dataBytes);

                if (dataString.ToLower() != "exit")
                    Console.WriteLine(dataString);
                else
                    connected = false;
            }
        }
    }
}

Sender code:

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;

class UDPSender
{
    static void Main(string[] args)
    {
        using (UdpClient client = new UdpClient())
        {
            bool connected = true;

            while (connected)
            {
                string dataString = Console.ReadLine();
                byte[] dataBytes = Encoding.UTF8.GetBytes(dataString);
                client.Send(dataBytes, dataBytes.Length, new IPEndPoint(IPAddress.Broadcast, 9998));
                if (dataString.ToLower() == "exit")
                    connected = false;
            }
        }
    }
}
Matías
Oh, BTW, it's in csharp, you didn't specified any language ^_^
Matías