using System; using System.Collections.Generic; using System.Net; using System.Net.Sockets; using System.Text; using BlubbFish.Utils; namespace BroadcastReciever { class Program { private readonly IPAddress s_mcastAddress; private readonly Int32 s_mcastPort; private Socket s_mcastSocket; private MulticastOption s_mcastOption; public Program(String[] args) { CmdArgs.Instance.SetArguments(new Dictionary() { { "adapter", new CmdArgs.VaildArguments(CmdArgs.ArgLength.Touple, true) }, { "multicast", new CmdArgs.VaildArguments(CmdArgs.ArgLength.Touple, false, "224.0.24.1") } }, args); if(!CmdArgs.Instance.HasAllRequiredArguments()) { Console.Error.WriteLine(CmdArgs.Instance.GetUsageList("BroadcastReciever.exe")); _ = Console.ReadLine(); return; } this.s_mcastAddress = IPAddress.Parse(CmdArgs.Instance.GetArgumentData("multicast")); this.s_mcastPort = 11000; // Start a multicast group. this.StartMulticast(); // Display MulticastOption properties. this.MulticastOptionProperties(); // Receive broadcast messages. this.ReceiveBroadcastMessages(); } private void StartMulticast() { try { this.s_mcastSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); IPAddress localIPAddr = IPAddress.Parse(CmdArgs.Instance.GetArgumentData("adapter")); //IPAddress localIP = IPAddress.Any; EndPoint localEP = new IPEndPoint(localIPAddr, this.s_mcastPort); this.s_mcastSocket.Bind(localEP); // Define a MulticastOption object specifying the multicast group // address and the local IPAddress. // The multicast group address is the same as the address used by the server. this.s_mcastOption = new MulticastOption(this.s_mcastAddress, localIPAddr); this.s_mcastSocket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, this.s_mcastOption); } catch(Exception e) { Console.WriteLine(e.ToString()); _ = Console.ReadLine(); return; } } private void MulticastOptionProperties() { Console.WriteLine("Current multicast group is: " + this.s_mcastOption.Group); Console.WriteLine("Current multicast local address is: " + this.s_mcastOption.LocalAddress); } private void ReceiveBroadcastMessages() { Boolean done = false; Byte[] bytes = new Byte[100]; IPEndPoint groupEP = new(this.s_mcastAddress, this.s_mcastPort); EndPoint remoteEP = new IPEndPoint(IPAddress.Any, 0); try { Console.WriteLine("Waiting for multicast packets......."); Console.WriteLine("Enter ^C to terminate."); while(!done) { Int32 length = this.s_mcastSocket.ReceiveFrom(bytes, ref remoteEP); Console.WriteLine("Received broadcast from \"{0}\" [{1}]: {2}", groupEP.ToString(), length, Encoding.ASCII.GetString(bytes, 0, bytes.Length)); } this.s_mcastSocket.Close(); } catch(Exception e) { Console.WriteLine(e.ToString()); _ = Console.ReadLine(); return; } } static void Main(String[] args) => _ = new Program(args); } }