Issue
I need to convert a string "00:11:22:33:44:55" to an uint8_t[6] representing a mac. I tried on my own, read somewhere char can be casted to uint8_t, but I'm kinda exhausted to try on my own. :(
Maybe there is a function in the kernel which does what I want.
If not, here is my code, what do I do wrong?
char * cleaned_mac =NULL;
char * extractMac(unsigned char * shared_user_buffer, size_t offset) {
char * buffer = kmalloc(17, GFP_KERNEL);
cleaned_mac = kmalloc(13, GFP_KERNEL);
int i = 0;
strncpy(buffer, shared_user_buffer + offset, 17);
printk("BUFFER [%s]\n", buffer);
while (*buffer && i < 12) {
if (isxdigit(*buffer)) {
printk("BUFFER [%c]\n", *buffer);
cleaned_mac[i] = *buffer;
printk("CLEANED BUFFER [%c]\n", *cleaned_mac);
i++;
}
++buffer;
}
cleaned_mac[12]=0x00;
printk("CLEANED BUFFER [%s]\n", cleaned_mac);
return cleaned_mac;
}
calling it like:
uint8_t * mac;
mac = extractMac(shared_user_buffer, strlen(tmq_server_prefix));
printk(KERN_DEBUG "MAC[%s]\n", mac);
printk(KERN_DEBUG "MAC[%02x:%02x:%02x:%02x:%02x:%02x]\n", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
so when I give "08:00:27:19:1f:02" in the function the result is:
Oct 13 17:41:28 client2 kernel: [ 1953.179271] CLEANED BUFFER [080027191f02]
Oct 13 17:41:28 client2 kernel: [ 1953.179273] MAC[080027191f02]
Oct 13 17:41:28 client2 kernel: [ 1953.179276] MAC[30:38:30:30:32:37]
So 08 became 30 and 38 ? Why is that?
Solution inspired from Dave (thank you):
uint8_t * cleaned_mac = NULL;
uint8_t * extractMac(unsigned char * shared_user_buffer, size_t offset) {
char *c;
char * buffer = kmalloc(17, GFP_KERNEL);
int p = 0;
const char * sep = ":";
cleaned_mac = kmalloc(ETH_ALEN * sizeof(uint8_t), GFP_KERNEL);
strncpy(buffer, shared_user_buffer + offset, 17);
while ((c = strsep(&buffer, sep))) {
cleaned_mac[p++] = simple_strtol(c, NULL, 16);
}
return cleaned_mac;
}
Usage then:
uint8_t * mac;
mac = extractMac(shared_user_buffer, strlen(tmq_server_prefix));
printk(KERN_DEBUG "---------------MAC [%02x:%02x:%02x:%02x:%02x:%02x]\n",
mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
Solution
Tokenize the string, and call strtol
on each result
char *c;
int p = 0;
for(c=strtok(buffer, ",");c;c=strtok(NULL, ","))
mac[p++] = strtol(c, NULL, 16);
Answered By - Dave Answer Checked By - Senaida (WPSolving Volunteer)