forked from ClassicDIY/ModbusTool
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUDPBroadcaster.cs
More file actions
60 lines (55 loc) · 1.74 KB
/
UDPBroadcaster.cs
File metadata and controls
60 lines (55 loc) · 1.74 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using ModbusLib.Protocols;
namespace ModbusSlave
{
public class UDPBroadcaster
{
private Thread _thread;
public bool _running = true;
private int selectedPort;
public void SendDatagrams(int p)
{
this.selectedPort = p;
_thread = new Thread(Worker);
_thread.Start();
}
public void Stop()
{
_running = false;
}
protected void Worker()
{
IPHostEntry ipHost = Dns.GetHostEntry(Dns.GetHostName());
try
{
UdpClient udpSocket = new UdpClient(4626);
IPEndPoint ip = new IPEndPoint(IPAddress.Broadcast, 4626);
udpSocket.EnableBroadcast = true;
udpSocket.DontFragment = true;
udpSocket.MulticastLoopback = false;
var add = Dns.GetHostAddresses(Dns.GetHostName()).First(a => a.AddressFamily == AddressFamily.InterNetwork);
var bytes = add.GetAddressBytes();
byte[] port = new byte[2];
port[0] = (byte)(selectedPort & 0x00ff);
port[1] = (byte)((selectedPort >> 8) & 0x00ff);
byte[] buf = bytes.Concat(port).ToArray();
while (_running)
{
udpSocket.Send(buf, buf.Length, ip);
Thread.Sleep(3000);
}
udpSocket.Close();
}
catch (Exception ex)
{
String msg = ex.Message;
}
}
}
}