Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Diagnostics;
- using System.Net;
- using System.Net.Sockets;
- using UnityEngine;
- using Debug = UnityEngine.Debug;
- public static class WakeOnLan
- {
- public static void WakeUp(string macAddress, string ipAddress, string subnetMask)
- {
- UdpClient client = new UdpClient();
- Byte[] datagram = new byte[102];
- for (int i = 0; i <= 5; i++)
- {
- datagram[i] = 0xff;
- }
- string[] macDigits = null;
- if (macAddress.Contains("-"))
- {
- macDigits = macAddress.Split('-');
- }
- else if (macAddress.Contains("."))
- {
- macDigits = macAddress.Split('.');
- }
- else if (macAddress.Contains(":"))
- {
- macDigits = macAddress.Split(':');
- }
- if (macDigits.Length != 6)
- {
- Debug.Log("Incorrect MAC address supplied!");
- }
- int start = 6;
- for (int i = 0; i < 16; i++)
- {
- for (int x = 0; x < 6; x++)
- {
- datagram[start + i * 6 + x] = (byte)Convert.ToInt32(macDigits[x], 16);
- }
- }
- IPAddress address = IPAddress.Parse(ipAddress);
- IPAddress mask = IPAddress.Parse(subnetMask);
- IPAddress broadcastAddress = address.GetBroadcastAddress(mask);
- Debug.Log("WAKE ON LAN - address " + address);
- Debug.Log("WAKE ON LAN - mask " + mask);
- Debug.Log("WAKE ON LAN - broadcastAddress " + broadcastAddress);
- Debug.Log("WAKE ON LAN - datagram " + datagram);
- client.Send(datagram, datagram.Length, broadcastAddress.ToString(), 3);
- }
- public static IPAddress GetBroadcastAddress(this IPAddress address, IPAddress subnetMask)
- {
- byte[] ipAdressBytes = address.GetAddressBytes();
- byte[] subnetMaskBytes = subnetMask.GetAddressBytes();
- if (ipAdressBytes.Length != subnetMaskBytes.Length)
- throw new ArgumentException("Lengths of IP address and subnet mask do not match.");
- byte[] broadcastAddress = new byte[ipAdressBytes.Length];
- for (int i = 0; i < broadcastAddress.Length; i++)
- {
- broadcastAddress[i] = (byte)(ipAdressBytes[i] | (subnetMaskBytes[i] ^ 255));
- }
- return new IPAddress(broadcastAddress);
- }
- }
Add Comment
Please, Sign In to add comment