Tuesday, January 26, 2010

Wake On LAN


Wake On LAN is a feature on some NIC cards that allow you to boot up your computer via network byte packages sent through your PC. In my NetPinger application I've been working on I've incorporated this feature. You have to find the MAC Address of a given PC, and then with the MAC/Machine Address you'll be able to send the WakeUp. To verify if you have this on your NIC card, turn your PC off, and see if your NIC Card still stays lit up after you shutdown. Once the NetPinger App is finished I'll post the source code on the internet for download.


using System.Net.Sockets;
[DllImport("iphlpapi.dll", ExactSpelling = true)]



static extern int SendARP(int DestIP, int SrcIP, byte[] pMacAddr, ref uintPhyAddrLen);
static DirectoryContext domainContext =
new DirectoryContext(DirectoryContextType.Domain);
[System.Runtime.InteropServices.DllImport("Iphlpapi.dll", EntryPoint ="SendARP")]
internal extern static Int32 SendArp(Int32 destIpAddress, Int32srcIpAddress, byte[] macAddress, ref Int32 macAddressLength);
public static System.Net.NetworkInformation.PhysicalAddressGetMacFromIP(System.Net.IPAddress IP)
{
if (IP.AddressFamily != System.Net.Sockets.AddressFamily.InterNetwork)
throw new ArgumentException("suppoerts just IPv4 addresses");
Int32 addrInt = IpToInt(IP);
Int32 srcAddrInt = IpToInt(IP);
byte[] mac = new byte[6]; // 48 bit
int length = mac.Length;
int reply = SendArp(addrInt, srcAddrInt, mac, ref length);
if (reply != 0)
throw new System.ComponentModel.Win32Exception(reply);
return new System.Net.NetworkInformation.PhysicalAddress(mac); ;
}
private static Int32 IpToInt(System.Net.IPAddress IP)
{
byte[] bytes = IP.GetAddressBytes();
return BitConverter.ToInt32(bytes, 0);
}
static byte[] GetMACAddress(string hostNameOrAddress)

{
IPHostEntry hostEntry = Dns.GetHostEntry(hostNameOrAddress);
if (hostEntry.AddressList.Length == 0)
return null; // We were not able to resolve given hostname / address
byte[] macAddr = new byte[6];
uint macAddrLen = (uint)macAddr.Length;
if (SendARP((int)hostEntry.AddressList[0].Address, 0, macAddr, refmacAddrLen) != 0)
return null; // The SendARP call failed
return macAddr;
}


private void WakeUp(string x)
{
byte[] macAddress = GetMACAddress(x);

List packet = new List();

for (int i = 0; i <>
packet.Add(0xFF);

for (int i = 0; i <>
packet.AddRange(macAddress);
UdpClient client = new UdpClient();
client.Connect(IPAddress.Broadcast, 7);

client.Send(packet.ToArray(), packet.Count);
}

No comments:

Post a Comment