一、前言
在某些项目中,需要通过随机数的方式获取随机mac。
下面记录一下方法。
二、实现过程
/* ************************************************************************
* Filename: random.c
* Description:
* Version: 1.0
* Created: 2023年03月06日 20时37分07秒
* Revision: none
* Compiler: gcc
* Author: YOUR NAME (),
* Company:
* ************************************************************************/
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <malloc.h>
#include <time.h>
#define ALOGD(fmt, ...) {printf("[D][%s:%d] "fmt"\n", __FUNCTION__, __LINE__, ##__VA_ARGS__);}
#define ALOGE(fmt, ...) {printf("[E][%s:%d] "fmt"\n", __FUNCTION__, __LINE__, ##__VA_ARGS__);}
#define ALOGI(fmt, ...) {printf("[I][%s:%d] "fmt"\n", __FUNCTION__, __LINE__, ##__VA_ARGS__);}
/* 生成随机mac */
static int random_ether_addr(unsigned char *mac, const int len)
{
if (len < 6) { // EtherAddr is 6 byte
ALOGE("mac len = %d, error!\n", len);
return -1;
}
time_t t;
srand((unsigned) time(&t));
unsigned long ethaddrLow, ethaddrHigh;
/*
* setting the 2nd LSB in the most significant byte of
* the address makes it a locally administered ethernet
* address
*/
ethaddrHigh = (unsigned long)(rand() & 0xfeff) | 0x0200;
ethaddrLow = (unsigned long)rand();
mac[0] = ethaddrHigh >> 8; /* 8 : create first mac's address */
mac[1] = ethaddrHigh & 0xff;
mac[2] = ethaddrLow >> 24; /* 24 : create third mac's address */
mac[3] = (ethaddrLow >> 16) & 0xff; /* 16 : create fourth mac's address */
mac[4] = (ethaddrLow >> 8) & 0xff; /* 8 : create fifth mac's address */
mac[5] = ethaddrLow & 0xff;
mac[0] &= 0xfe; /* clear multicast bit */
mac[0] |= 0x02; /* set local assignment bit (IEEE802) */
return 0;
}
/* mac 格式化 */
static int mac_to_string(char *mac_str, unsigned char *mac, const int mac_len)
{
if (mac_len < 6) { // EtherAddr is 6 byte
ALOGE("mac length = %d, error!\n", mac_len);
return -1;
}
if (sprintf(mac_str, "%02X:%02X:%02X:%02X:%02X:%02X",
mac[0x0], mac[0x1], mac[0x2],
mac[0x3], mac[0x4], mac[0x5]) < 0) {
ALOGE("sprintf mac_str failed!\n");
return -2;
}
return 0;
}
int main(int argc, char *argv[])
{
int ret = -1;
unsigned char mac[6] = {0};
char *buf = NULL;
buf = (char *)malloc(sizeof(char) * 32);
if (NULL == buf)
{
ALOGD("can not alloc mem for buf!!");
return -1;
}
memset(buf, 0x00, sizeof(char) * 32);
/* step1: 获取随机mac */
random_ether_addr(mac, sizeof(mac));
/* step2: mac格式化 */
mac_to_string(buf, mac, sizeof(mac));
ALOGD("random mac: [%s]", buf);
if (buf != NULL)
{
free(buf);
buf = NULL;
}
return 0;
}