Linux下如何获取MAC地址

Linux下如何获取MAC地址
int get_mac(char *mac ,int len_limit)
{
struct ifreq ifreq;
int sock;

if((sock = socket(AF_INET ,SOCK_STREAM ,0)) < 0)
{
LOGSTREAM( gp_log[LOGAPP], LOGPOSI << "|socket Error" );
return -1;
}


strcpy(ifreq.ifr_name ,"em1");
if(ioctl(sock,SIOCGIFHWADDR ,&ifreq) < 0)
{
close(sock);
LOGSTREAM( gp_log[LOGAPP], LOGPOSI << "|ioctl Error" );
return -1;
}
close(sock);

return snprintf(mac ,len_limit ,"%02X:%02X:%02X:%02X:%02X:%02X",
(unsigned char)ifreq.ifr_hwaddr.sa_data[0] ,
(unsigned char)ifreq.ifr_hwaddr.sa_data[1] ,
(unsigned char)ifreq.ifr_hwaddr.sa_data[2] ,
(unsigned char)ifreq.ifr_hwaddr.sa_data[3] ,
(unsigned char)ifreq.ifr_hwaddr.sa_data[4] ,
(unsigned char)ifreq.ifr_hwaddr.sa_data[5] );
}


之前没有close掉sock描述符,会导致sock泄露

你可能感兴趣的:(c++,Linux)