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
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 + ".");
}
}
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";
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With