将 MAC 地址字符串转换为字节






2.50/5 (4投票s)
代码片段将 MAC 地址字符串格式转换为字节
介绍
inet_addr
和 inet_ntoa
已经可用于 IP 地址处理。这里,我提供了与此类似的功能,用于处理 MAC 地址。
这段代码片段将 MAC 地址字符串转换为字节数组,并将字节数组转换为 MAC 地址字符串。
背景
我在互联网上搜索过,但没有找到这样的函数,所以在这里发布出来供大家使用。
Using the Code
代码本身即自解释的。
const char cSep = '-'; //Bytes separator in MAC address string like 00-aa-bb-cc-dd-ee
/*
This function accepts MAC address in string format and returns in bytes.
it relies on size of byAddress and it must be greater than 6 bytes.
If MAC address string is not in valid format, it returns NULL.
NOTE: tolower function is used and it is locale dependent.
*/
unsigned char* ConverMacAddressStringIntoByte
(const char *pszMACAddress, unsigned char* pbyAddress)
{
for (int iConunter = 0; iConunter < 6; ++iConunter)
{
unsigned int iNumber = 0;
char ch;
//Convert letter into lower case.
ch = tolower (*pszMACAddress++);
if ((ch < '0' || ch > '9') && (ch < 'a' || ch > 'f'))
{
return NULL;
}
//Convert into number.
// a. If character is digit then ch - '0'
// b. else (ch - 'a' + 10) it is done
// because addition of 10 takes correct value.
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;
}
}
/* Store result. */
pbyAddress[iConunter] = (unsigned char) iNumber;
/* Skip cSep. */
++pszMACAddress;
}
return pbyAddress;
}
/*
This function converts Mac Address in Bytes to String format.
It does not validate any string size and pointers.
It returns MAC address in string format.
*/
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;
}
历史
- 2009年4月8日:首次发布