Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Agent.cs
- UdpClient client = new UdpClient(9); // UdpClient that listens to port 9
- IPEndPoint endPoint = new IPEndPoint(IPAddress.Any, 0); // Receive from any IP
- TcpClient answerer;
- byte[] received;
- byte[] answerNonMagicPacket = Encoding.UTF8.GetBytes("WolUtilities");
- byte[] answerMagicPacket = Encoding.UTF8.GetBytes("ShuttingDown");
- string mac = GetMachineMacAddress();
- Console.WriteLine("Listening to magic packets... MAC address of this machine is: {0}", mac);
- while (true)
- {
- received = client.Receive(ref endPoint); // Blocks until message is got
- if (IsMagicPacket(received, mac))
- {
- Console.WriteLine($"Received a magic packet from {endPoint.Address}:{endPoint.Port}, answering.");
- using (answerer = new TcpClient(endPoint.Address.ToString(), endPoint.Port))
- {
- NetworkStream stream = answerer.GetStream();
- stream.Write(answerMagicPacket, 0, answerMagicPacket.Length);
- }
- }
- else
- {
- Console.WriteLine($"Received a non-magic packet from {endPoint.Address}:{endPoint.Port}, answering.");
- using (answerer = new TcpClient(endPoint.Address.ToString(), endPoint.Port))
- {
- NetworkStream stream = answerer.GetStream();
- stream.Write(answerNonMagicPacket, 0, answerNonMagicPacket.Length);
- }
- }
- }
- Program.cs
- Console.WriteLine("Hello, World!\nSending Wol packet");
- WakeOnLan wol = new WakeOnLan("IP", Port, "MacAddress");
- wol.Send();
- IPEndPoint endPoint = new IPEndPoint(IPAddress.Any, 0); // Receive from any IP
- TcpListener listener = null;
- try
- {
- listener = new TcpListener(IPAddress.Parse("127.0.0.1"), 9);
- listener.Start();
- byte[] received = new byte[512];
- string data;
- using (TcpClient client = listener.AcceptTcpClient())
- {
- Console.WriteLine("Answerer connected!");
- NetworkStream stream = client.GetStream();
- int i;
- while ((i = stream.Read(received, 0, received.Length)) != 0)
- {
- // Translate data bytes to a UTF8 string.
- data = Encoding.UTF8.GetString(received, 0, i);
- Console.WriteLine("Received: {0}", data);
- if (data == "WolUtilities")
- {
- Console.WriteLine("The client received a non-magic packet, success.");
- break;
- }
- else if (data == "ShuttingDown")
- {
- Console.WriteLine("The client received a magic-packet, success.");
- break;
- }
- else
- {
- Console.WriteLine(data);
- Console.WriteLine("I don't know what to do with that :(");
- }
- }
- }
- }
- catch (Exception ex)
- {
- Console.WriteLine($"{ex.GetType()}: {ex.Message}");
- }
- finally
- {
- Console.ReadLine();
- }
Advertisement
Add Comment
Please, Sign In to add comment