广播

发布于 2024-07-16 07:10:14 字数 85 浏览 7 评论 0原文

如果可能的话,有人可以向我提供使用 UDP 发送和接收广播消息的代码或链接吗?

我一直陷入一个问题,希望你们能帮助我解决它。 谢谢

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

樱桃奶球 2024-07-23 07:10:14

这是一个 C# 示例:

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'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 + ".");   
   }
}
甚是思念 2024-07-23 07:10:14

以下是广播发送者和接收者的示例代码。

它应该可以轻松移植到任何可以访问标准 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";
}

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";
}
不必在意 2024-07-23 07:10:14

我不会发布代码,只是提出几点意见:

  1. 发送 UDP 广播就像发送单播数据包 - 只是目标地址不同。 这可以是INADDR_BROADCAST (255.255.255.255),但这可能会在具有多个网络接口的系统上导致问题。 最好发送到您要发送的接口的特定广播地址。 唯一重要的警告是,您可能需要在操作系统允许发送广播之前设置 SO_BROADCAST 套接字选项。

  2. 接收 UDP 广播完全就像接收单播数据包一样。 不需要特殊代码,但您应该将接收器绑定到 INADDR_ANY

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.

我一直都在从未离去 2024-07-23 07:10:14

我刚刚开始学习这一点,但这是我的第一个工作示例,它可能会对您有所帮助。

收件人代码:

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;
            }
        }
    }
}

发件人代码:

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;
            }
        }
    }
}

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;
            }
        }
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文