views:

78

answers:

2

I have a simple function that passes a variable "var" as a u_char array. I have no difficulty printing that array.

    printf("%2.2x:%2.2x:%2.2x:%2.2x:%2.2x:%2.2x", var[0], var [1], var[2], var[3], var[4], var[5]);

Prints the mac address out just the way I like it.

I cannot for the life of me figure out the proper way to store this Mac address and compare it with another string. Ideally, this is what I'm after:

global OldString="00:00:00:00:00:00"

NewString=getCurrentMacAddress();

if OldString = Newstring then ignore else some_function

But I have been banging my head against a wall all day just trying to store this "var" output as a string. I tried strcpy, I tried looping with a for loop, I tried everything I could find on google from malloc to global declaration in lieu of passing the value to the function.

Any help is appreciated. I'm completely new to C and just trying to write a simple little tool... It's taking way longer than it should.

+3  A: 

snprintf() will use the same format string and parameters as the printf() call you already have working.

char NewString[] = "00:00:00:00:00:00";  // initializing with this string is just a lazy
                                         //   way to get the right amount of storage

snprintf( NewString, sizeof( NewString), "%2.2x:%2.2x:%2.2x:%2.2x:%2.2x:%2.2x", var[0], var [1], var[2], var[3], var[4], var[5]);
Michael Burr
I cannot say how thankful I am - I have been ********ing around with this for way too long. Thank you thank you thank you.
Andrew J. Freyer
+1 for guessing correctly what the OP wanted.
Alok
+1  A: 

You have two main options:

  1. Store (or convert) the global OldString into an array of 6 byte values, and then use memcmp() to compare those 6 bytes against the 6 bytes in 'var'.

  2. Convert 'var' into a string using snprintf() or something similar, and then use 'strcmp()' to compare that string agains OldString.

Both mechanisms work. Which is better depends on how you are going to use the values. If you mainly need the binary form, then option 1 is likely better; if you mainly need the string form, option 2 is better.

(Michael Burr gives an accurate way to use snprintf(), though in theory you should check its return value to ensure that it behaved correctly.)

Jonathan Leffler