user1727270
user1727270

Reputation: 433

How to convert Mac string to a Byte address in C

I want to take a MAC address from the command line (e.g., "00:0d:3f:cd:02:5f") and convert it to a six-byte unsigned char array. How do I do this?

Upvotes: 16

Views: 27043

Answers (3)

yuanjianpeng
yuanjianpeng

Reputation: 328

There's standard c library funtion do this

  #include <netinet/ether.h>

  char *ether_ntoa(const struct ether_addr *addr);
  struct ether_addr *ether_aton(const char *asc);

The structure ether_addr is defined in <net/ethernet.h> as:

  struct ether_addr {
        uint8_t ether_addr_octet[6];
  }

Upvotes: 1

renonsz
renonsz

Reputation: 591

Without built-in functions and error handling simply:

unsigned char mac[6];
for( uint idx = 0; idx < sizeof(mac)/sizeof(mac[0]); ++idx )
{
    mac[idx]  = hex_digit( mac_str[     3 * idx ] ) << 4;
    mac[idx] |= hex_digit( mac_str[ 1 + 3 * idx ] );
}

Input is actually 3*6 bytes with \0.

unsigned char hex_digit( char ch )
{
    if(             ( '0' <= ch ) && ( ch <= '9' ) ) { ch -= '0'; }
    else
    {
        if(         ( 'a' <= ch ) && ( ch <= 'f' ) ) { ch += 10 - 'a'; }
        else
        {
            if(     ( 'A' <= ch ) && ( ch <= 'F' ) ) { ch += 10 - 'A'; }
            else                                     { ch = 16; }
        }
    }
    return ch;
}

Upvotes: 3

CrazyCasta
CrazyCasta

Reputation: 28302

On a C99-conformant implementation, this should work

unsigned char mac[6];

sscanf(macStr, "%hhx:%hhx:%hhx:%hhx:%hhx:%hhx", &mac[0], &mac[1], &mac[2], &mac[3], &mac[4], &mac[5]);

Otherwise, you'll need:

unsigned int iMac[6];
unsigned char mac[6];
int i;

sscanf(macStr, "%x:%x:%x:%x:%x:%x", &iMac[0], &iMac[1], &iMac[2], &iMac[3], &iMac[4], &iMac[5]);
for(i=0;i<6;i++)
    mac[i] = (unsigned char)iMac[i];

Upvotes: 29

Related Questions