Sending Wake-on-LAN Magic Packets from C#

I present, with little introduction, the MACAddress class. Within you will find simple test and conversion methods, with a single, simple to use method for sending a WOL ‘Magic’ Packet.

 

// MACAddress Class (Sending WOL 'Magic' Packets)
// Written by John Storer II (Feb 20, 2012)
//
// Feel free to use/modify this code as you wish, without liability.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Net;

namespace SendWOLPacket
{
    public class MACAddress
    {
        /// <summary>
        /// Test a MACAddress byte Array.
        /// </summary>
        /// <param name="macAddress"></param>
        /// <returns></returns>
        public static bool Test(byte[] macAddress) {
            if (macAddress == null) return false;
            if (macAddress.Length != 6) return false;

            return true;
        }

        /// <summary>
        /// Test a MACAddress string.
        /// </summary>
        /// <param name="macAddress"></param>
        /// <returns></returns>
        public static bool Test(string macAddress) {
            var valid_chars = "0123456789ABCDEFabcdef";

            if (string.IsNullOrEmpty(macAddress)) return false;
            if (macAddress.Length != 12) return false;

            foreach (var c in macAddress) {
                if (valid_chars.IndexOf(c) < 0) {
                    return false;
                }
            }

            return true;
        }

        /// <summary>
        /// Parse a MACAddress string into a byte array.
        /// </summary>
        /// <param name="macAddress"></param>
        /// <returns></returns>
        public static byte[] Parse(string macAddress) {
            byte[] mac = new byte[6];

            if (!Test(macAddress))
                throw new ArgumentException(
                    "Invalid MACAddress string.",
                    "macAddress",
                    null);

            for (var i = 0; i < 6; i++) {
                var t = macAddress.Substring((i * 2), 2);
                mac[i] = Convert.ToByte(t, 16);
            }

            return mac;
        }

        /// <summary>
        /// Attempt to parse a MACAddress string
        ///   without throwing an Exception.
        /// </summary>
        /// <param name="macAddress"></param>
        /// <param name="Address"></param>
        /// <returns></returns>
        public static bool TryParse(string macAddress, out byte[] Address) {
            try {
                Address = Parse(macAddress);
                return true;
            }
            catch {
                Address = null;
                return false;
            }
        }

        /// <summary>
        /// Convert a byte array MACAddress to a string.
        /// </summary>
        /// <param name="macAddress"></param>
        /// <returns></returns>
        public static string ToString(byte[] macAddress) {
            if (!Test(macAddress))
                throw new ArgumentException(
                    "Invalid MACAddress byte array.",
                    "macAddress",
                    null);

            return BitConverter.ToString(macAddress).Replace("-", "");
        }


        /// <summary>
        /// Sends a Wake-On-LAN 'magic' packet to
        ///   the specified MACAddress string.
        /// </summary>
        /// <param name="macAddress"></param>
        public static void SendWOLPacket(string macAddress) {

            if (!Test(macAddress))
                throw new ArgumentException(
                    "Invalid MACAddress string.",
                    "macAddress",
                    null);
            
            byte[] mac = Parse(macAddress);

            SendWOLPacket(mac);
        }

        /// <summary>
        /// Sends a Wake-On-LAN 'magic' packet to
        ///   the specified MACAddress byte array.
        /// </summary>
        /// <param name="macAddress"></param>
        public static void SendWOLPacket(byte[] macAddress) {

            if (!Test(macAddress))
                throw new ArgumentException(
                    "Invalid MACAddress byte array.",
                    "macAddress",
                    null);

            // WOL 'magic' packet is sent over UDP.
            using (UdpClient client = new UdpClient()) {

                // Send to: 255.255.255.0:40000 over UDP.
                client.Connect(IPAddress.Broadcast, 40000);

                // Two parts to a 'magic' packet:
                //     First is 0xFFFFFFFFFFFF,
                //     Second is 16 * MACAddress.
                byte[] packet = new byte[17 * 6];

                // Set to: 0xFFFFFFFFFFFF.
                for (int i = 0; i < 6; i++) {
                    packet[i] = 0xFF;
                }

                // Set to: 16 * MACAddress
                for (int i = 1; i <= 16; i++) {
                    for (int j = 0; j < 6; j++) {
                        packet[i * 6 + j] = macAddress[j];
                    }
                }

                // Send WOL 'magic' packet.
                client.Send(packet, packet.Length);
            }
        }

    }
}

Using this code is as simple as (assuming you have a form, a button named bSend and a text box named tbMACAddress):

private void bSend_Click(object sender, EventArgs e) {
    try {
        MACAddress.SendWOLPacket(tbMACAddress.Text);

        MessageBox.Show(
            string.Format("Packet Sent to '{0}'", tbMACAddress.Text));
    }
    catch (Exception Error) {
        MessageBox.Show(
            string.Format("Error:\n\n{0}", Error.Message), "Error");
    }
            
}

Why write a class to send WOL Packets? Mainly because I needed to wake up a PC at home remotely, if I really needed it. Also, someone here at work said, “I need to send WOL to this laptop, but I don’t have the Altiris Console handy,” to which I replied:

Challenge Accepted

Because who doesn't like a good challenge?

Some Myths about Introverts

Saw this on Google+ and had to share my insights on it.

Myth #1 – Introverts don’t like to talk.
This is not true. Introverts just don’t talk unless they have something to say. They hate small talk. Get an introvert talking about something they are interested in, and they won’t shut up for days.

[I am very much like that. Very true. I also have difficulty listening to people who take seemingly forever just to get to the point of their story. Spit it out already!]

Myth #2 – Introverts are shy.
Shyness has nothing to do with being an Introvert. Introverts are not necessarily afraid of people. What they need is a reason to interact. They don’t interact for the sake of interacting. If you want to talk to an Introvert, just start talking. Don’t worry about being polite.

[I think shyness does play a small part in it, but mostly it's mainly an excuse to stand back and investigate the situation.]

Myth #3 – Introverts are rude.
Introverts often don’t see a reason for beating around the bush with social pleasantries. They want everyone to just be real and honest. Unfortunately, this is not acceptable in most settings, so Introverts can feel a lot of pressure to fit in, which they find exhausting.

[Most people don't realize how difficult it is to resist the urge to speak our mind at all times. It can quickly make a social interaction intense.]

Myth #4 – Introverts don’t like people.
On the contrary, Introverts intensely value the few friends they have. They can count their close friends on one hand. If you are lucky enough for an introvert to consider you a friend, you probably have a loyal ally for life. Once you have earned their respect as being a person of substance, you’re in.

[Couldn't have said it better myself. I'm big with the social media. I have a G+ and a Facebook profile, plus a LinkedIn and probably much more than I can remember. I tend to "trim the fat" and remove those people who I have no desire or need to interact with, so that only those who have earned and deserve my attention receive it. It's also a good reason why I keep those profiles mostly private.]

Myth #5 – Introverts don’t like to go out in public.
Nonsense. Introverts just don’t like to go out in public FOR AS LONG. They also like to avoid the complications that are involved in public activities. They take in data and experiences very quickly, and as a result, don’t need to be there for long to “get it.” They’re ready to go home, recharge, and process it all. In fact, recharging is absolutely crucial for Introverts.

[Also very true. I prefer being at home, or being at a friends house. Being out in public tends to just slowly eat away at my patience. If I have to endure big crowds, I quickly become intensely focused on getting out of them, and getting to a 'safe' place.]

Myth #6 – Introverts always want to be alone.
Introverts are perfectly comfortable with their own thoughts. They think a lot. They daydream. They like to have problems to work on, puzzles to solve. But they can also get incredibly lonely if they don’t have anyone to share their discoveries with. They crave an authentic and sincere connection with ONE PERSON at a time.

[Agreed. It's actually quite difficult not to daydream whilst others are talking to me. Mental gymnastics. Not being able to share my thoughts and 'discoveries' with someone who gets me, who understands why I think the way I do, tends to make me slightly more nuts crazy insane. It's definitely a problem that goes down straight to the core of an introvert's personality.]

Myth #7 – Introverts are weird.
Introverts are often individualists. They don’t follow the crowd. They’d prefer to be valued for their novel ways of living. They think for themselves and because of that, they often challenge the norm. They don’t make most decisions based on what is popular or trendy.

[I think, therefore I am. And I definitely think I'm strange. But since I tend to surround myself with people that understand me, I guess I become the relative norm!]

Myth #8 – Introverts are aloof nerds.
Introverts are people who primarily look inward, paying close attention to their thoughts and emotions. It’s not that they are incapable of paying attention to what is going on around them, it’s just that their inner world is much more stimulating and rewarding to them.

[True. Most of the time the stories I create in my own head are much more fantastic than those of others. And unfortunately, when I find a story that captivates me, it's a difficult job to pay attention to other, less interesting conversations.]

Myth #9 – Introverts don’t know how to relax and have fun.
Introverts typically relax at home or in nature, not in busy public places. Introverts are not thrill seekers and adrenaline junkies. If there is too much talking and noise going on, they shut down. Their brains are too sensitive to the neurotransmitter called Dopamine. Introverts and Extroverts have different dominant neuro-pathways. Just look it up.

[Reading the Wikipedia entry on that particular topic leads me to believe that this response is backwards; that extroverts are more sensitive to dopamine levels, which is they they seek out stimulation instead of being content. Otherwise, yes, we prefer to stay at home to relax.]

Myth #10 – Introverts can fix themselves and become Extroverts.
A world without Introverts would be a world with few scientists, musicians, artists, poets, filmmakers, doctors, mathematicians, writers, and philosophers. That being said, there are still plenty of techniques an Extrovert can learn in order to interact with Introverts. (Yes, I reversed these two terms on purpose to show you how biased our society is.) Introverts cannot “fix themselves” and deserve respect for their natural temperament and contributions to the human race. In fact, one study (Silverman, 1986) showed that the percentage of Introverts increases with IQ.

[I don't know why other people would see introversion as a bad thing. Introverts tend to be smarter and better adjusted to the world around them, especially since we choose with such care where and with whom we spend our time with.]

Comments Off

o.O Where have I been!?

Oh wow. Where did I go? I’ve been so busy I forgot completely about these little posts I make. Guess it’s time to start posting again.

Here soon I should have a few more goodies, including a little screen shot tool called… Screen Shot Tool. Yeah, I’m creative. But they guys at work like it, so I did something right.

Folders, files and poorly described exceptions

You know, sometimes exceptions returned in C# are so irritatingly vague or indirect that it takes longer than I’d like to solve the problem.

For example, I’ve been attempting to loop through a large set of directories on a network share, for a list of users in Active Directory. I have both an File/Folder indexing library, and an Active Directory library to help speed up development.

foreach (User Account in Accounts) {
    if (!Directory.Exists(Account.HomeDirectory)) continue;

    List<DirectoryInfo> folders = new List<DirectoryInfo>();
    List<FileInfo> files = new List<FileInfo>();

    Folders.Index(
        new DirectoryInfo(Account.HomeDirectory),
        ref folders,
        ref files);

    files.Reverse();
    folders.Reverse();

    foreach (FileInfo fi in files) {
        if (fi.Exists) fi.Delete();
    }

    foreach (DirectoryInfo di in folders) {
        if (di.Exists) di.Delete(true);
    }
}

Irritatingly, it kept returning a “Access is denied” error on the first folder that it attempted to delete. I, of course, have had not nearly enough sleep to deal with this sort of obscure issue, but I plowed on. I ran the code under a domain admin account; that didn’t fix it. I added the existence checks and a bit of debugging output to find where it was failing exactly.

Unable to force the issue, I checked the folder that it was failing on, and the folder was “root\My Videos”. Properties showed “Read-only for files in this folder”.

*facepalm*

Here’s the fixed code. Essentially it sets the FileAttributes of the files and folders it attempts to delete to FileAttributes.Normal, thereby bypassing the “Access is Denied” error (which IMHO should be a “Unable to delete – folder is read-only”!) and allowing the deletion.

foreach (User Account in Accounts) {
    if (!Directory.Exists(Account.HomeDirectory)) continue;

    List<DirectoryInfo> folders = new List<DirectoryInfo>();
    List<FileInfo> files = new List<FileInfo>();

    Folders.Index(
        new DirectoryInfo(Account.HomeDirectory),
        ref folders,
        ref files);

    files.Reverse();
    folders.Reverse();

    foreach (FileInfo fi in files) {
        fi.Attributes = FileAttributes.Normal;
        if (fi.Exists) fi.Delete();
    }

    foreach (DirectoryInfo di in folders) {
        di.Attributes = FileAttributes.Normal;
        if (di.Exists) di.Delete(true);
    }
}

I’m guessing that if I still have issues, I’ll probably have to take ownership of the files/folders to delete them. Not a great start to the day.

Update 1:

I found what looks to be a “Privilege Enabling” library. This is definitely something I shall be adding to my toolkit.

public static void TakeOwnership(DirectoryInfo di) {
    Process p = Process.GetCurrentProcess();

    using (new ProcessPrivileges.PrivilegeEnabler(p, Privilege.TakeOwnership)) {
        DirectorySecurity ds = di.GetAccessControl();
        ds.SetOwner(WindowsIdentity.GetCurrent().User);
        di.SetAccessControl(ds);
    }
}

Update 2:

Wow. After trying to take ownership as above, I still had difficulties with certain “RECYCLER” files/folders, and taking ownership apparently wasn’t enough. Here’s the full-on, brute-force, take-control method:

public static void TakeOwnership(ref DirectoryInfo di) {
    Process p = Process.GetCurrentProcess();
    SecurityIdentifier si = WindowsIdentity.GetCurrent().User;

    // Raise the process' access privileges.
    using (new ProcessPrivileges.PrivilegeEnabler(p, Privilege.TakeOwnership, Privilege.Security)) {
        // Get access rules.
        DirectorySecurity ds = di.GetAccessControl();

        // Take "full control" of everything.        
        FileSystemAccessRule fsaRule = new FileSystemAccessRule(
            si,
            FileSystemRights.Delete | FileSystemRights.Modify,
            InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,
            PropagationFlags.None,
            AccessControlType.Allow);

        // Remove previous access rules.
        ds.PurgeAccessRules(si);

        // Add the new access rules.
        ds.AddAccessRule(fsaRule);

        // Take ownership
        ds.SetOwner(si);

        // Set the access rules to the object.
        di.SetAccessControl(ds);
    }
}

Comments Off

Revisionist History

I’ve been going through all the old posts and attempting to update them to match both the category list and the styles. It’ll take a bit of time, but until then, here’s my Harry Potter and the Deathly Hallows Part 2 review. Yes, there will be tonnes of spoilers. You’ve been warned. Also, why don’t you know the story yet, anyway? You should already know how this movie ends!

I am both underwhelmed and overwhelmed. Does that just make me whelmed? Is that even a thing? Do the horrible changes they make verses the beautifully told stories cancel each other out?

I am overwhelmed simply because it is the last movie and we’re pretty much leaving this world behind now. The CG, practical and special effects were all appropriately awesome. The acting has gotten better and better over the years.You really get a good feel of how far they’ve all come on their journey this last decade.

However, I am underwhelmed by all of the changes they made. Much of what made the story so great in the book was gutted, and while this can’t be avoided when the book is that long, some of their edits made absolutely no sense.

For example, the scene in which Harry and Voldemort fight for the last time is completely and utterly pointless and anti-climatic. In the book, this scene takes place in front of the whole (or what’s left of the) school. The real feeling of accomplishment and the weight of the victory can be felt. In the movie, the character split up so much that nothing important happens between more than three people. Harry Potter and Voldy fight by themselves in a stretched out mano-a-snako wand-lightning battle and flying around randomly in smoke. Neville doesn’t get to chop off Nagini‘s head until the dynamic duo Hermione Granger and Ron Weasley battle it on some stairs and get to cower appropriately. The “NOT MY DAUGHTER YOU BITCH” scene in the book becomes an almost whispered line (relative to all the other sounds happening around them) and the emotion of the fight between Molly Weasley and Bellatrix fails completely. There were so many times that I thought the audience in the theatre was going to cheer, but then it seemed like everyone was embarrassed because the movie didn’t really hit the emotional beats it deserved.

The changes they made baffles me, because they would have been so much better literally just cribbed straight from the books. Why the script writer (and/or the actress) changed the feel of the Molly/Bellatrix fight astounds me. Why they felt Harry needed to fight Voldy alone, where no one could see and/or verify his victory over the greatest evil wizard ever is completely bonkers! The extra scenes add literally nothing but extra time wasted to the story, and it degrades the source material.

Other baffling changes arrive in the story of Dumbledore‘s family. I get why they didn’t have time, but why would you bring it up at all if you weren’t going to explain it even a little?. A name is dropped, an accusation flung, but we have no idea why these things are there. And the elves, obviously minus Dobby, show up nowhere in the movie, where they are a major part of the book’s big fight. In the opposite of the last, it would have made sense to add at least a passing reference to them, considering that they made so much a point of them in several movies, because otherwise it is as if Dobby’s death and Treacher’s change from villian to servant to savior completely worthless now.

Now, it’s not as if this is a complete waste of a movie – on the contrary, in every other respect it excelled my expectations. Maggie Smith‘s acting is supurb, knowing that the whole time she was battling cancer during production, and especially the line where she says, in a very girl-ish way, “I’ve always wanted to say that spell!”. Alan Rickman‘s Snape is probably the highlight of the whole movie, as you see every single bit of him shattered in the pensive sequence. Also, his death scene was respectably brutal and hidden tactfully behind frosted glass, but the full weight of it is completely felt. The epilogue scene, while short and not truly important is any way, was wonderfully done, especially the almost lack of makeup and body modifications needed to make it seem legitimate. (I only wish they’d mentioned “Prof. Longbottom”, even if in passing) I guess it helps that the actors themselves have grown enough for it.

If I had to rate the movie, I’d say definitely a 3 out of 5, it was both awesome and infuriating in it’s execution. I only wish they’d consulted the book a little more for ideas instead of padding or trimming things out improperly.

Comments Off

Forgetfulness is… wait, what was I saying?

Unfortunately, I forgot a small detail with the switch-over. All of the media is still on the old server. So apparently all the old posts I imported will be pointing to incorrect media locations. I’ve got a local copy of it, now, as I was able to FTP in via IP Address (since jstorer2.com now points here), so eventually I’ll either have to edit the post or upload the new media.

Now back to your regularly scheduled ignoring of my posts. ;)

Comments Off

The new blog, same as the old blog.

So, here’s the rub. My old website, jstorer2.com, will be ending it’s three year run in August. So I will be moving my blog here, which seems sensible considering how much work/money it costs to host my own. So ignore the ads and enjoy the new location of my blog.

Please realize that all of the links to media will probably be broken. I no longer have access to the old stuff, so I’ll try to fix what I can.

Comments Off

Thunderstorms

We’re actually going through a thunderstorm right now, so I thought I’d get some audio together of the bolts-in-question’s passage through the atmosphere. Here’s an MP3 of some of the best ones, edited to remove as much noise and background rain as possible, without destroying the best lightning-strikes heard today.

[Edit: Of course, now that I've switched to wordpress.com, I am no longer allowed to upload MP3s without paying a little extra a month. We'll see if I can't scrounge up a few bucks to enjoy the privilege.]

Comments Off

Mesmerizing Time-Lapse Shows Every Asteroid Discovered Since 1980 VIDEO

Wow. There are a lot of NEO objects out there. Common wisdom is to believe that space is vast and empty, but near stars it seems to be false. Of course, with the distances involved, it really is sparse; but from an outside observer, it’s a lot more crowded in here than most think it is.

Below is a video of all the asteroids discovered from 1980 to 2010. Around the 1990 mark, large swaths of asteroids were being discovered by automated system.

Mesmerizing Time-Lapse Shows Every Asteroid Discovered Since 1980 VIDEO.

Comments Off