Click here to Skip to main content
Click here to Skip to main content

Wake On Lan sample for C#

, 27 Oct 2003
Rate this:
Please Sign up or sign in to vote.
Wake On Lan utility using C#.

Introduction

It's strange but I failed to find on the Internet any WOL sample written in C#. So I spent some time making a program to that purpose. It's very simple but it works OK (in our intranet at least).

For waking computers, I use Magic Packet (MAC address of network adapter repeated 16 times).

The actual functionality is implemented like this:

Code

using System;
using System.Net.Sockets;

//we derive our class from a standart one
public class WOLClass:UdpClient    
{
    public WOLClass():base()
    { }
    //this is needed to send broadcast packet
    public void SetClientToBrodcastMode()    
    {
      if(this.Active)
       this.Client.SetSocketOption(SocketOptionLevel.Socket,
                                 SocketOptionName.Broadcast,0);
    }
 }
 
...
//now use this class
 //MAC_ADDRESS should  look like '013FA049'
 private void WakeFunction(string MAC_ADDRESS)   
 {
      WOLClass client=new WOLClass();
      client.Connect(new 
         IPAddress(0xffffffff),  //255.255.255.255  i.e broadcast
         0x2fff); // port=12287 let's use this one 
      client.SetClientToBrodcastMode();
      //set sending bites
      int counter=0;
      //buffer to be send
      byte[] bytes=new byte[1024];   // more than enough :-)
     //first 6 bytes should be 0xFF
     for(int y=0;y<6;y++)
        bytes[counter++]=0xFF;
     //now repeate MAC 16 times
     for(int y=0;y<16;y++)
     {
         int i=0;
         for(int z=0;z<6;z++)
         {
              bytes[counter++]= 
                  byte.Parse(MAC_ADDRESS.Substring(i,2),
                  NumberStyles.HexNumber);
              i+=2;
         }
     }

     //now send wake up packet
     int reterned_value=client.Send(bytes,1024);
 }

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

Share

About the Author

maxburov

Satellite Provider Satellite Provider
No Biography provided

Comments and Discussions

 
QuestionNot working on my system.. PinmemberMember 1002944612-May-13 22:58 
GeneralWorks with WOW PinmemberDavid j rundle15-May-12 4:34 
GeneralThanks! PinmemberAnthraxx NL22-Jan-10 10:33 
GeneralOther example and some theory Pinmembermemos-software24-Jun-08 20:31 
GeneralError PinmemberChristian Rasmussen11-Jun-08 3:11 
GeneralRe: Error PinmemberIan_E15-Jun-08 12:35 
GeneralRe: Error PinmemberRandy_Miller12-Jul-08 6:14 
Some routers will pass what is called a directed broadcast. We use Wake on Lan extensively where I work and have made no special changes to our routers to pass broadcasts. You have to figure out what the broadcast address for the subnet you are sending to is then send to that address. For us the simple convertIP method works. Our routers think it is a regular IP Address and route it to the correct subnet then send it to all machines on that subnet(the last octet being 255).The machines whose Mac is sent wakes up the rest ignore the broadcast. This may not always work but its worth a try. Code snippet:
 
public void SendWakeUp(string MachineName, string IPAddress, string MacAddress)
{
IPAddress WOLIPAddress = convertIP(IPAddress); //Convert to system broadcast IP
byte[] WOLMacAddr = Mac2Byte(MacAddress);// Convertmac address string to byte array
byte[] WOLPayLoad = CreatePayload(WOLMacAddr);// create a byte array payload
IPEndPoint WOLEndPoint = new IPEndPoint(WOLIPAddress, 7); //Create an Ip Endpoint
int Sucess = SendUDP(WOLPayLoad, WOLEndPoint);
}
public IPAddress convertIP(string _IPAddress)
{
string BroadcastAddress = "";
string[] Octets = _IPAddress.Split(new Char[] { '.' });
Octets[3] = "255";
BroadcastAddress = Octets[0] + "." + Octets[1] + "." + Octets[2] + "." + Octets[3];
System.Net.IPAddress wolIPAddr = IPAddress.Parse(BroadcastAddress);
return wolIPAddr;
}
protected static byte[] Mac2Byte(string strMacAddress)
{
string macAddr;
byte[] macBytes = new byte[BYTELENGHT];
//remove all non 0-9, A-F, a-f characters
macAddr = Regex.Replace(strMacAddress, @"[^0-9A-Fa-f]", "");
//check if it is now a valid mac adress
if (!(macAddr.Length == BYTELENGHT * 2))
throw new ArgumentException("Mac Adress must be " + (BYTELENGHT * 2).ToString() + " digits of 0-9, A-F, a-f characters in length.");
string hex;
for (int i = 0; i < macBytes.Length; i++)
{
hex = new String(new Char[] { macAddr[i * 2], macAddr[i * 2 + 1] });
macBytes[(i)] = byte.Parse(hex, System.Globalization.NumberStyles.HexNumber);
}
return macBytes;
}
protected static byte[] CreatePayload(byte[] macAddress)
{
byte[] payloadData = new byte[HEADER + MAGICPACKETLENGTH * BYTELENGHT];
for (int i = 0; i < HEADER; i++)
{
payloadData[i] = byte.Parse("FF", System.Globalization.NumberStyles.HexNumber);
}
for (int i = 0; i < MAGICPACKETLENGTH; i++)
{
for (int j = 0; j < BYTELENGHT; j++)
{
payloadData[((i * BYTELENGHT) + j) + HEADER] = macAddress[j];
}
}
return payloadData;
}
protected static int SendUDP(byte[] Payload, IPEndPoint EndPoint)
{
int byteSend;
//create a new client socket...
Socket socketClient = new Socket(EndPoint.AddressFamily, SocketType.Dgram, ProtocolType.Udp);
try
{
//open connection...
socketClient.Connect(EndPoint);
//send MagicPacket(TM)...
byteSend = socketClient.Send(Payload, 0, Payload.Length, SocketFlags.None);

}
catch (SocketException ex)
{
throw ex;
}
finally
{
socketClient.Close();
}
return byteSend;
}
GeneralThanks! Pinmemberdevcow11-Jun-07 7:16 
GeneralWorks great ! PinmemberA.J.Bauer11-Mar-07 6:32 
Generalfor broadcasting Pinmemberplato2926-Jun-06 22:16 
Generalbroadcasting Pinmemberplato2926-Jun-06 21:42 
GeneralIP Broadcasting PinmemberSave My Soul - (SMS)27-Dec-05 22:29 
GeneralThanks for the sample PinmemberRadoslav Bielik6-Jan-04 11:05 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web04 | 2.8.140827.1 | Last Updated 28 Oct 2003
Article Copyright 2003 by maxburov
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid