Host Information Code Snippet

Apr 15, 2007

When you are running a Unix based operating system, you have a neat command called uname that will display information about your computer. If you want it to display everything, then execute it with the -a option.

$ uname -a
Darwin chris-barbers-computer.local 8.9.1 Darwin Kernel Version 8.9.1:
Thu Feb 22 20:55:00 PST 2007; root:xnu-792.18.15~1/RELEASE_I386 i386 i386

This command outputs the following information:

  • Operating system name (-s)
  • Nodename (network name) (-n)
  • Operating system release (-r)
  • Operating system version (-v)
  • Machine hardware name (-m)
  • Generic processor type (-p)

Suppose you want to display that information from within your own application. Whether it’s written in C/C++, PHP, Coldfusion, Java, whatever, you could just execute the uname command six times to parse each bits of information, but that’s not very elegant, especially if you are using writing a C/C++ application.

With a little C code, you can grab this info and dump it in a format that is easy to parse. I’ve actually written it with C++, but you can adapt it to C.

// main.cpp

#include <iostream>
#include <sys/utsname.h>

using namespace std;

int main(void)
{
    utsname u;
    uname(&u);

    cout << "<hostinfo>" << endl;
    cout << "<system-name>" << u.sysname << "</system-name>" << endl;
    cout << "<release>" << u.release << "</release>" << endl;
    cout << "<version>" << u.version << "</version>" << endl;
    cout << "<machine>" << u.machine << "</machine>" << endl;
    cout << "<node-name>" << u.nodename << "</node-name>" << endl;
    cout << "</hostinfo>" << endl;

    return 0;
}

Compile the code with gcc:

$ g++ -o hostinfo main.cpp

And when you run it you get:

$ ./hostinfo
<hostinfo>
<system-name>Darwin</system-name>
<release>8.9.1</release>
<version>Darwin Kernel Version 8.9.1: Thu Feb 22 20:55:00 PST 2007; root:xnu-792.18.15~1/RELEASE_I386</version>
<machine>i386</machine>
<node-name>chris-barbers-computer.local</node-name>
</hostinfo>

That should be easy enough to parse and display where ever you see fit. It doesn’t have to be XML either, you could output it as JSON, tab delimited, or whatever works best. This code works on Mac OS X and Linux.

So, why on Earth would you want to output this? I use it in a C++ application for dump information about the host into the top of the log files. Maybe you have a dozen web application servers and you want a quick way to figure out what kernel version is installed on each. Hopefully someone can come up with something interesting to do with this.


No Comments

No comments yet.

RSS feed for comments on this post. TrackBack URL

Sorry, the comment form is closed at this time.