Reading ARP entries with C#

Recently, I needed to locate a device on my network using ARP (Address Resolution Protocol). I could have written code that directly uses the protocol to discover the device, by essentially probing a range of addresses on my network until it found the right one. But, that proved to be too much work. So, I decided to use Window’s arp command line tool.

To demonstrate the arp command, open a command prompt, type the following, and then press enter:

arp -a

This is a simple way to display a list of devices and their associated MAC addresses. The goal of my C# program would be to invoke this command and parse the output.

To begin, I wrote this simple method:

public static StreamReader ExecuteCommandLine(String file, String arguments = "") {
    ProcessStartInfo startInfo = new ProcessStartInfo();
    startInfo.CreateNoWindow = true;
    startInfo.WindowStyle = ProcessWindowStyle.Hidden;
    startInfo.UseShellExecute = false;
    startInfo.RedirectStandardOutput = true;
    startInfo.FileName = file;
    startInfo.Arguments = arguments;

    Process process = Process.Start(startInfo);

    return process.StandardOutput;
}

Given the name of a program to execute, and a list of arguments to pass to that program, the above function returns the StreamReader associated with the output of the program. The next step is to parse the output and find the device you want:

var arpStream = Utility.ExecuteCommandLine(“arp”, “-a”);

// Consume first three lines
for (int i = 0; i < 3; i++) { arpStream.ReadLine(); } // Read entries while (!arpStream.EndOfStream) { var line = arpStream.ReadLine().Trim(); while (line.Contains(" ")) { line = line.Replace(" ", " "); } var parts = line.Split(' '); // Match device's MAC address if (parts[1].Replace("-", "").ToUpper().Trim() == "UPPERCASE_MAC_ADDRESS_TO_FIND_GOES_HERE") { // Your device is on the network // Access its IP address with: parts[0].Trim() } } [/csharp] The first line makes use of the function I defined above to execute the arp command and get its standard output stream. If you've tried the arp command out for yourself, you will notice that the first three lines are garbage. The next three lines of code account for this by advancing past the garbage lines. Finally, I iterate over each entry in the table and try to match the given MAC address. If the MAC address is found, you can fetch the IP address of the associated device. Please note that this code has no error checking. I'm not sure, for example, what would happen if the arp tool lists no devices, or if the user doesn't have administrative privileges.

The DorkbotPDX PCB Order

I’ve just recently gotten into electronics. For the longest time, I’ve enjoyed using breadboards to prototype simple circuits with 555 timers, LEDs, and other little components. Recently, my ability to move beyond simple circuits was tested by a new project. Long story short, I had to develop a custom PCB (printed circuit board) to drive multiple servos, among other devices. The board would actually be a shield that plugs into an Arduino Uno, which is an awesome, cheap, and easy-to-use microcontroller. A “shield” is simply a board that extends the capabilities that the Arduino provides.

Side-note: If you have even a remote interest in electronics, then get yourself an Arduino. At SparkFun, the latest Uno, the R3, is less than $30.

To design the actual circuit, I first tried using Fritzing. This program is really cool because you can design your circuits in a breadboard view, which actually visualizes what the breadboard looks like with all the wires and components plugged in. I was able to prototype most of the circuit really quickly. But, I ran into a snag when I needed parts that the Fritzing library didn’t provide. That was a shame, because Fritzing has a really nice fabrication service (Fritzing Fab) built right in.

I ended up using the freeware version of EAGLE– the project I was doing was for educational purposes, so I didn’t have to buy a full version of the software. The neat thing about EAGLE is that its library comes with a ridiculous amount of parts, from nearly all of the major manufacturers. I coupled this with the SparkFun library, which contains parts definitions for most the parts that SparkFun sells, and was up and running quickly.

When it came time to print the actual board, I researched various fabrication services. Eventually, I decided on the DorkbotPDX PCB Order. There are so many things that I like about it:

  • It’s $5/square inch. No setup fees or hidden costs. Shipping within the United States is free via USPS. Worldwide shipping is extra.
  • The fee per square inch is paid only once, but you get three boards! For example, a 4 square inch board (approx. the size of an Arduino shield) costs $20 for three copies, shipping included!
  • The boards are purple!
  • Made in the USA
  • The quality is excellent
Yeah, it really is that cheap and awesome; I’m not the only one that has noticed. Check out these reviews for the service:
I wrote this short post as a bit of free advertising for the service. Laen, the guy that runs it, is really doing the community a favor by orchestrating this. If you have a board that you’d like printed, I encourage you to use this service.

wrapDetector: Automatically detect word-wrappable characters

I’d like to announce my latest plugin: wrapDetector. wrapDetector is designed to do one thing: return a list of characters at which a line can wrap.

I’ve created the project at BitBucket: https://bitbucket.org/MostThingsWeb/wrapdetector. If you find it interesting, give it a try. I look forward to hearing your feedback and suggestions.

Zend Framework Pitfall: Non-working ErrorController (404 errors)

I’ve begun my journey into the world of Zend Framework, and like a lot of other people out there, I’m clueless. Nevertheless, I am slowly (very slowly, I’ll add) using it to develop my first project.

I’ve already encountered a few problems that I’ve been able to fix. They were very annoying to track down; usually just a single misconfigured setting or incorrectly named file. The upside to this suffering is that I can share the solutions I’ve found with others who might be having the same problems.

Problem

Whenever I browsed to a non-existent page in my application, the ErrorController would not catch the error. Instead, I got a 404 error.

Solution

Set AllowOveride to All in your httpd.conf file.

Explanation

The ErrorController, usually located at application/controllers/ErrorController.php is designed to display errors that your application encounters in a pretty, readable way. By default, it prints out the error message and stack trace, along with some other information. So, why wasn’t I getting this when I browsed to a non-existent page? The solution in my case was quite simple.

The single misconfigured settings, as described in the Solution, wasn’t allowing other .htaccess files to override settings already declared in the httpd.conf file. Zend Tool, the tool I used to create the basic skeleton for my project, had created its own .htaccess file in my public folder. This file contains directives for redirecting every request to the index.php file, where your Zend Framework application is initialized and started. Every request is routed here, no matter the URL. So, visiting http://www.myZendFrameworkSite.site/controller/action really just redirects to that index.php file, with controller/action as the argument.

When I was visiting a non-existent page, the request wasn’t routed to index.php so Zend couldn’t complain that the controller/action didn’t exist. Instead, the browser complained that it couldn’t find the file, which wouldn’t have existed anyway even if the controller/action did.

Credit

Took a while to hunt down the solution. Turned out it was at the top of a Zend Framework tutorial by Rob Allen, here. Thank you Rob!

 

Hiding tab headers on a TabControl in C#

After browsing around a little bit, I found an interesting solution if you need to hide the tab headers on a tab control. I found it here, posted on the MSDN social forums by “nobugz” (Hans Passant). Here is his solution:

class YourTabControl : TabControl{
    protected override void WndProc(ref Message m){
        // Hide tabs by trapping the TCM_ADJUSTRECT message
        if (m.Msg == 0x1328 && !DesignMode)
            m.Result = (IntPtr)1;
        else
            base.WndProc(ref m);
    }
}

Basically, you define your own class that extends TabControl. The custom class overrides the WndProc method, which is responsible for processing Windows messages sent to windows and controls. The new version filters out the message which is responsible for drawing the tab headers. Very clever.

To use it, you can make a normal TabControl using the designer. Then, in the Designer code, change the following line (in the InitializeComponent method):

this.tabControl1 =  new System.Windows.Forms.TabControl();

to

this.tabControl1 =  new YourTabControl();

Finally, near the bottom of the Designer code should be a line that looks like this:

private System.Windows.Forms.TabControl tabControl1;

Change it to:

private YourTabControl tabControl1;

Another clever thing about this is that, as you will notice, tab headers are still visible while in Design mode.

Automatically embedding images in CSS: CSS Image Embedder

I’ve created a quick, simple tool that converts CSS file references (like url(images/someimage.png)) to inline image data (like url('data:....')). Written in C#, and available as an open source download (see below), the tool is a point-and-click alternative to manually making the data URIs.

A screenshot of the CSS Image Embedder
Screenshot

To use the tool, follow these three steps:

  1. Open the CSS file you want to work with.
  2. Resolve the image references that CSS Image Embedder finds to actual files. Use Manual Resolve to manually resolve a single reference, or Auto Resolve to automatically resolve multiple references.
  3. Save the CSS file. The image references are automatically inlined when you save it.

In case you didn’t know, the data URI scheme lets you inline file references anywhere a `src` attribute is normally used. Wikipedia has a good description, as well as examples.

More instructions will follow soon on the Wiki, so stay tuned. Please comment if you like the tool, or have suggestions. Enjoy!

Download/read about it at BitBucket: https://bitbucket.org/MostThingsWeb/css-image-embedder

Converting CSS selectors to XPath selectors with C#: css2xpath

While working with HtmlAgilityPack to build a web scrapper/crawler, I noticed something: I hate XPath. It’s big, clunky, and verbose. After a bit of searching, I found a neat online app: http://css2xpath.appspot.com/. As the name suggests, it converts CSS selectors to XPath selectors. The only problem is that I wanted a client-side solution.

A little more searching, and I find css2xpath. It accomplishes the same thing as the web service, but does it client side, in JavaScript. So, I ported it to C#. And here we are.

The original css2xpath, written by Andrea Giammarchi, is a single JavaScript function that uses a series of Regexes to transform a CSS selector, step-by-step, into an XPath selector. My version does the same thing, and uses the same Regexes and transformation functions, but is written in C#.

Housed in a single static class, the handful of functions contained within are easy to use. For example:

css2xpath.Transform('#id');

Is all that it takes. That expression will yield: //*[@id='anID'].

Other features include the ability for you to define your own transformation rules. See the link below for more information and how to download. Enjoy!

Download/read about it at BitBucket: https://bitbucket.org/MostThingsWeb/css2xpath

Bayes Filtering in Javascript

I’ve been trying to put together a Bayesian classifier in JavaScript, mostly for spam filtering purposes. It didn’t turn out very well. So, I Googled for such a thing and found this: http://www.onemanclapping.org/2008/10/bayes-filtering-in-javascript.html. It looks very well done and I’d recommend it (from the brief testing I’ve done with it), although I’d like to point out that the code is not very portable. Luckily, according to the author’s website, http://www.dusbabek.org/~garyd/, the project is public domain. My plan is to make the code into a fully portable library, and then repost it for all to use. Stay tuned; I will post it soon!