1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

C#でUDPブロードキャストパケット受信

Posted at

参考記事

実装

UDPブロードキャストパケットを受信してエコーするタスクを常駐させるサンプルです。

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

namespace udp
{
    public class udpSample {

        public void start()
        {
            Task.Run(() => BroadcastReceiver()); // UDPブロードキャストパケット受信タスク起動
        }

        private void BroadcastReceiver()
        {
            var endPoint = new IPEndPoint(IPAddress.Any, 4000); // すべてのアドレス監視するためIPAddress.Anyを指定

            using (UdpClient udpClient = new UdpClient(endPoint)) {
                while(true) {
                    var buff = udpClient.Receive(ref endPoint);  // 受信(同期)
                    udpClient.Send(buff, buff.Length, endPoint); // 受信内容をエコー
                }
            }
        }
    }
}

IPEndPointにusing System.Net;が、
UdpClientにusing System.Net.Sockets;が必要になります。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?