SafeDispatch/TCPClientService/UdpMulticast.cs
2024-02-22 18:43:59 +02:00

216 lines
7.6 KiB
C#

using System;
using System.Text;
using System.Net.Sockets;
using System.Net;
using System.Threading;
using System.Security.Cryptography;
using System.IO;
using System.Diagnostics;
namespace WindowsService1
{
public class UdpMulticast
{
private Socket s;
private Thread listenThread;
private string mcastGroup;
private int port;
private bool working = false;
private bool useThreadPool = false;
public UdpMulticast(string mcastGroup, int port)
{
this.mcastGroup = mcastGroup;
this.port = port;
}
private void Listen_pool(object a)
{
Listen();
}
private void Listen()
{
while (working)
{
try
{
int recv = 0; ;
byte[] b = new byte[1024];
Thread.Sleep(1);
if (s != null)
recv = s.Receive(b);
else
break;//break if socket == null
if (recv == 0)
continue;//continue if return nr bytes == 0
if (OnNewDataRecv != null)
{
byte[] tmp = new byte[recv];
for (int i = 0; i < recv; i++)
{
tmp[i] = b[i];
}
byte[] decByte = Encryption.Decrypt(tmp);
if (this.OnNewDataRecv != null)
this.OnNewDataRecv(decByte, decByte.Length);
}
if (s == null)
{
break;
}
}
catch (SocketException ex)
{
Utils.WriteEventLog("Safemobile", "UdpMulticast Listen SOCKET EXCEPTION " + ex.ToString(), EventLogEntryType.Error, 23456);
break;
}
catch (ThreadAbortException ex)
{
Utils.WriteEventLog("Safemobile", "UdpMulticast Listen Thread Abort EXCEPTION " + ex.ToString(), EventLogEntryType.Error, 23456);
break;
}
catch (Exception ex)
{
Utils.WriteEventLog("Safemobile", "UdpMulticast Listen Exception" + ex.ToString(), EventLogEntryType.Error, 23456);
}
}
}
public delegate void newData4Send(byte[] data, int dataLen);
public event newData4Send OnNewDataRecv;
public bool StartListen(string localIP = null)
{
bool ret = false;
working = true;
try
{
IPAddress myIP = !string.IsNullOrWhiteSpace(localIP) ? IPAddress.Parse(localIP) : getPreferedIPAdress();
if (s == null)
{
s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
}
if (s != null)
{
Utils.WriteEventLog("Safemobile", "PORT multi cast :" + port, EventLogEntryType.Information, 34500);
IPEndPoint ipep = new IPEndPoint(IPAddress.Any, port);
s.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, 1);
s.Bind(ipep);
IPAddress ip = IPAddress.Parse(mcastGroup);
s.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(ip, IPAddress.Any));
s.SetSocketOption(SocketOptionLevel.IP,
SocketOptionName.MulticastTimeToLive, int.Parse("1"));
listenThread = new Thread(new ThreadStart(Listen));
listenThread.IsBackground = true;
}
if (listenThread != null)
listenThread.Start();
ret = true;
Utils.WriteEventLog("Safemobile",
$"++++++++++++++++++++++++++++++++++++++++++\nUdpMulticast bind on {mcastGroup}:{port} Ethernet: {myIP}\n++++++++++++++++++++++++++++++++++++++++++",
EventLogEntryType.Information, 23456);
}
catch (Exception ex)
{
Utils.WriteEventLog("Safemobile", "Ex:" + ex.ToString(), EventLogEntryType.Error, 23456);
}
return ret;
}
public static IPAddress getPreferedIPAdress()
{
IPAddress localIP = IPAddress.Parse("127.0.0.1");
Socket socket = null;
try
{
using (socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, 0))
{
socket.Connect("10.0.2.4", 65530);
IPEndPoint endPoint = socket.LocalEndPoint as IPEndPoint;
localIP = endPoint.Address;
}
}
catch (Exception ex)
{
Utils.WriteLine(ex.ToString(), ConsoleColor.DarkRed);
}
finally
{
if (socket != null)
socket.Dispose();
}
return localIP;
}
public void Send(byte[] data, int len)
{
if (s == null)
{
s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
}
if (s != null)
{
IPEndPoint ipep = new IPEndPoint(IPAddress.Parse(mcastGroup), port);
byte[] encByte = Encryption.Encrypt(data);
s.SendTo(encByte, encByte.Length, SocketFlags.None, ipep);
}
else Utils.WriteEventLog("Safemobile", "s is NULL", EventLogEntryType.Error, 23456);
}
public void Send_decoded(byte[] data, int len)
{
if (s == null)
{
s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
}
if (s != null)
{
IPEndPoint ipep = new IPEndPoint(IPAddress.Parse(mcastGroup), port);
s.SendTo(data, data.Length, SocketFlags.None, ipep);
}
else Utils.WriteEventLog("Safemobile", "s is NULL", EventLogEntryType.Error, 23456);
}
}
static public class Encryption
{
static byte[] bytes = ASCIIEncoding.ASCII.GetBytes("SafeMobi"); //DES 64bit !
static public byte[] Encrypt(byte[] inputArray)
{
DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();
MemoryStream memoryStream = new MemoryStream();
CryptoStream cryptoStream = new CryptoStream(memoryStream, cryptoProvider.CreateEncryptor(bytes, bytes), CryptoStreamMode.Write);
cryptoStream.Write(inputArray, 0, inputArray.Length);
cryptoStream.Close(); memoryStream.Close();
return memoryStream.ToArray();
}
static public byte[] Decrypt(byte[] DataToDecrypt)
{
DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();
MemoryStream memoryStream = new MemoryStream();
CryptoStream cryptoStream = new CryptoStream(memoryStream, cryptoProvider.CreateDecryptor(bytes, bytes), CryptoStreamMode.Write);
cryptoStream.Write(DataToDecrypt, 0, DataToDecrypt.Length);
cryptoStream.Close(); memoryStream.Close();
return memoryStream.ToArray();
}
}
}