Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Net;
- using System.Net.Sockets;
- using System.Text;
- using System.Threading.Tasks;
- namespace UDP
- {
- class Server
- {
- public static void Main()
- {
- string strIpAddress;
- IPAddress IpAddress = null;
- Boolean tryAgain = true;
- drawMenu();
- while (tryAgain)
- {
- tryAgain = true;
- Console.Write("Enter multicast address: ");
- strIpAddress = Console.ReadLine();
- try
- {
- IpAddress = IPAddress.Parse(strIpAddress);
- if (!IsInRange(IpAddress))
- {
- Console.WriteLine("Wrong multicast address, try again.");
- tryAgain = true;
- }
- else tryAgain = false;
- }
- catch (FormatException e)
- {
- Console.WriteLine("Wrong IP address, try again.");
- tryAgain = true;
- }
- }
- UdpClient client = new UdpClient();
- client.ExclusiveAddressUse = false;
- IPEndPoint localEp = new IPEndPoint(IPAddress.Any, 2222);
- client.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
- client.ExclusiveAddressUse = false;
- client.Client.Bind(localEp);
- client.JoinMulticastGroup(IpAddress);
- Console.WriteLine("Server started...\n\n");
- while (true)
- {
- Byte[] data = client.Receive(ref localEp);
- string strData = Encoding.Unicode.GetString(data);
- Console.WriteLine(strData);
- }
- }
- public static bool IsInRange(IPAddress address)
- {
- IPAddress lowerAddress = IPAddress.Parse("224.0.0.0");
- IPAddress higherAddress = IPAddress.Parse("239.255.255.255");
- byte[] lowerBytes = lowerAddress.GetAddressBytes();
- byte[] upperBytes = higherAddress.GetAddressBytes();
- byte[] addressBytes = address.GetAddressBytes();
- bool lower = true, higher = true;
- for (int i = 0; i < lowerBytes.Length && (lower || higher); i++)
- {
- if ((lower && addressBytes[i] < lowerBytes[i]) || (higher && addressBytes[i] > upperBytes[i]))
- return false;
- lower &= (addressBytes[i] == lowerBytes[i]);
- higher &= (addressBytes[i] == upperBytes[i]);
- }
- return true;
- }
- public static void drawMenu()
- {
- Console.WriteLine("\n\t******************************");
- Console.WriteLine( "\t* UDP Server *");
- Console.WriteLine( "\t******************************\n");
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement