A
Alex Buell
I have the following snippet (only works on Linux), which works
perfectly when I need to output only one hardware address at a time,
but when I have occasions to print two diffferent ones (i.e source and
destination hardware addresses), it will print two copies of the same
hardware address, which isn't what I wanted, and yes I do know why that
happens but my workarounds for this looks quite kludgy involving
separate character arrays for each address output.
Can anyone come up with a much better and a lot more elegant solution
than this?
Thanks, much appreciated!
/* cut here */
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <net/ethernet.h>
char *hardware_address_string(unsigned char *hardware_address)
{
static char buffer[ETH_ALEN * 5 + 2];
char *p = (char *)buffer;
unsigned char *q = (unsigned char *)hardware_address;
if (hardware_address)
{
for (; q < (hardware_address + ETH_ALEN); q++)
{
sprintf(p, "%02X", (unsigned char)*q);
p += 2;
if (q < hardware_address + ETH_ALEN - 1)
sprintf(p++, ":");
}
}
return buffer;
}
int main()
{
unsigned char addr1[] = { 0x0, 0x50, 0x56, 0xc0, 0x0, 0x01 };
unsigned char addr2[] = { 0x0, 0x0d, 0x56, 0x38, 0x97, 0x33 };
char buffer[80];
sprintf(buffer, "Addr1 = %s, addr2 = %s",
hardware_address_string(addr1),
hardware_address_string(addr2));
printf("%s\n", buffer);
return 0;
}
/* end of snippet */
perfectly when I need to output only one hardware address at a time,
but when I have occasions to print two diffferent ones (i.e source and
destination hardware addresses), it will print two copies of the same
hardware address, which isn't what I wanted, and yes I do know why that
happens but my workarounds for this looks quite kludgy involving
separate character arrays for each address output.
Can anyone come up with a much better and a lot more elegant solution
than this?
Thanks, much appreciated!
/* cut here */
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <net/ethernet.h>
char *hardware_address_string(unsigned char *hardware_address)
{
static char buffer[ETH_ALEN * 5 + 2];
char *p = (char *)buffer;
unsigned char *q = (unsigned char *)hardware_address;
if (hardware_address)
{
for (; q < (hardware_address + ETH_ALEN); q++)
{
sprintf(p, "%02X", (unsigned char)*q);
p += 2;
if (q < hardware_address + ETH_ALEN - 1)
sprintf(p++, ":");
}
}
return buffer;
}
int main()
{
unsigned char addr1[] = { 0x0, 0x50, 0x56, 0xc0, 0x0, 0x01 };
unsigned char addr2[] = { 0x0, 0x0d, 0x56, 0x38, 0x97, 0x33 };
char buffer[80];
sprintf(buffer, "Addr1 = %s, addr2 = %s",
hardware_address_string(addr1),
hardware_address_string(addr2));
printf("%s\n", buffer);
return 0;
}
/* end of snippet */