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_Client
- {
- class Client
- {
- public static void Main()
- {
- string strIpAddress, menuOption;
- IPAddress IpAddress = null;
- Boolean tryAgain = true;
- UdpClient udpclient = new UdpClient();
- drawMenu();
- Console.WriteLine("What do you want to do?");
- Console.WriteLine("\t1.\tMulticast\n\t2.\tBroadcast\n\tAny.\tExit");
- Console.Write("Your choice: ");
- menuOption = Console.ReadLine();
- if (menuOption.Equals("1"))
- {
- while (tryAgain)
- {
- tryAgain = true;
- Console.Write("Enter multicast address: ");
- strIpAddress = Console.ReadLine();
- try
- {
- IpAddress = IPAddress.Parse(strIpAddress);
- if (!isAddressValid(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.JoinMulticastGroup(IpAddress);
- }
- else if (menuOption.Equals("2"))
- {
- strIpAddress = "255.255.255.255";
- IpAddress = IPAddress.Parse(strIpAddress);
- }
- else System.Environment.Exit(-1);
- IPEndPoint remoteep = new IPEndPoint(IpAddress, 2222);
- Console.WriteLine("Send messages:");
- string text = "";
- while (true)
- {
- Console.Write("Text:");
- text = Console.ReadLine();
- if (String.IsNullOrEmpty(text)) break;
- byte[] data = Encoding.Unicode.GetBytes(text);
- udpclient.Send(data, data.Length, remoteep);
- Console.Write("rn");
- }
- }
- public static bool isAddressValid(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 Client *");
- Console.WriteLine( "\t******************************\n");
- }
- }
- }
Add Comment
Please, Sign In to add comment