Guest User

Untitled

a guest
Nov 21st, 2018
131
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.27 KB | None | 0 0
  1. using System;
  2. using System.Diagnostics;
  3. using System.Net;
  4. using System.Net.Sockets;
  5. using UnityEngine;
  6. using Debug = UnityEngine.Debug;
  7.  
  8. public static class WakeOnLan
  9. {
  10. public static void WakeUp(string macAddress, string ipAddress, string subnetMask)
  11. {
  12. UdpClient client = new UdpClient();
  13.  
  14. Byte[] datagram = new byte[102];
  15.  
  16. for (int i = 0; i <= 5; i++)
  17. {
  18. datagram[i] = 0xff;
  19. }
  20.  
  21. string[] macDigits = null;
  22.  
  23. if (macAddress.Contains("-"))
  24. {
  25. macDigits = macAddress.Split('-');
  26. }
  27. else if (macAddress.Contains("."))
  28. {
  29. macDigits = macAddress.Split('.');
  30. }
  31. else if (macAddress.Contains(":"))
  32. {
  33. macDigits = macAddress.Split(':');
  34. }
  35.  
  36. if (macDigits.Length != 6)
  37. {
  38. Debug.Log("Incorrect MAC address supplied!");
  39. }
  40.  
  41. int start = 6;
  42. for (int i = 0; i < 16; i++)
  43. {
  44. for (int x = 0; x < 6; x++)
  45. {
  46. datagram[start + i * 6 + x] = (byte)Convert.ToInt32(macDigits[x], 16);
  47. }
  48. }
  49.  
  50. IPAddress address = IPAddress.Parse(ipAddress);
  51. IPAddress mask = IPAddress.Parse(subnetMask);
  52. IPAddress broadcastAddress = address.GetBroadcastAddress(mask);
  53.  
  54. Debug.Log("WAKE ON LAN - address " + address);
  55. Debug.Log("WAKE ON LAN - mask " + mask);
  56. Debug.Log("WAKE ON LAN - broadcastAddress " + broadcastAddress);
  57. Debug.Log("WAKE ON LAN - datagram " + datagram);
  58.  
  59. client.Send(datagram, datagram.Length, broadcastAddress.ToString(), 3);
  60. }
  61.  
  62. public static IPAddress GetBroadcastAddress(this IPAddress address, IPAddress subnetMask)
  63. {
  64. byte[] ipAdressBytes = address.GetAddressBytes();
  65. byte[] subnetMaskBytes = subnetMask.GetAddressBytes();
  66.  
  67. if (ipAdressBytes.Length != subnetMaskBytes.Length)
  68. throw new ArgumentException("Lengths of IP address and subnet mask do not match.");
  69.  
  70. byte[] broadcastAddress = new byte[ipAdressBytes.Length];
  71. for (int i = 0; i < broadcastAddress.Length; i++)
  72. {
  73. broadcastAddress[i] = (byte)(ipAdressBytes[i] | (subnetMaskBytes[i] ^ 255));
  74. }
  75.  
  76. return new IPAddress(broadcastAddress);
  77. }
  78. }
Add Comment
Please, Sign In to add comment