Introduction
inet_addr
and inet_ntoa
are already available for IP address processing. Here, I put the same functionalities for MAC address.
This code snippet converts MAC address string into bytes array and bytes array into MAC address' string.
Background
I searched the internet but I could not find such a function so I publish it here for every one.
Using the Code
The code is self explanatory.
const char cSep = '-';
unsigned char* ConverMacAddressStringIntoByte
(const char *pszMACAddress, unsigned char* pbyAddress)
{
for (int iConunter = 0; iConunter < 6; ++iConunter)
{
unsigned int iNumber = 0;
char ch;
ch = tolower (*pszMACAddress++);
if ((ch < '0' || ch > '9') && (ch < 'a' || ch > 'f'))
{
return NULL;
}
iNumber = isdigit (ch) ? (ch - '0') : (ch - 'a' + 10);
ch = tolower (*pszMACAddress);
if ((iConunter < 5 && ch != cSep) ||
(iConunter == 5 && ch != '\0' && !isspace (ch)))
{
++pszMACAddress;
if ((ch < '0' || ch > '9') && (ch < 'a' || ch > 'f'))
{
return NULL;
}
iNumber <<= 4;
iNumber += isdigit (ch) ? (ch - '0') : (ch - 'a' + 10);
ch = *pszMACAddress;
if (iConunter < 5 && ch != cSep)
{
return NULL;
}
}
pbyAddress[iConunter] = (unsigned char) iNumber;
++pszMACAddress;
}
return pbyAddress;
}
char *ConvertMacAddressInBytesToString(char *pszMACAddress,
unsigned char *pbyMacAddressInBytes)
{
sprintf(pszMACAddress, "%02x%c%02x%c%02x%c%02x%c%02x%c%02x",
pbyMacAddressInBytes[0] & 0xff,
cSep,
pbyMacAddressInBytes[1]& 0xff,
cSep,
pbyMacAddressInBytes[2]& 0xff,
cSep,
pbyMacAddressInBytes[3]& 0xff,
cSep,
pbyMacAddressInBytes[4]& 0xff,
cSep,
pbyMacAddressInBytes[5]& 0xff);
return pszMACAddress;
}
History
- 8th April, 2009: Initial post