通过soket获取mac地址

bool readMac(const char* if_name, uint8_t* mac)
{
    bool ret = false;
    struct ifreq m_ifreq;
    int32_t sock = 0;
    sock = socket(AF_INET, SOCK_STREAM, 0);
    if (sock < 0) {
        printf("socket error\n");
        return false;
    }                       
    memcpy(m_ifreq.ifr_name, if_name,sizeof(m_ifreq.ifr_name) - 1);
    ret = ioctl(sock, SIOCGIFHWADDR, &m_ifreq);
    if (ret < 0) {
        printf("ioctl error:%d\n", ret);
        return false;
    }
    snprintf((char*)mac, 13, "%02x%02x%02x%02x%02x%02x", (uint8_t)m_ifreq.ifr_hwaddr.sa_data[0],
            (uint8_t)m_ifreq.ifr_hwaddr.sa_data[1],
            (uint8_t)m_ifreq.ifr_hwaddr.sa_data[2],
            (uint8_t)m_ifreq.ifr_hwaddr.sa_data[3],
            (uint8_t)m_ifreq.ifr_hwaddr.sa_data[4],
            (uint8_t)m_ifreq.ifr_hwaddr.*[5]);
    return true;
}

你可能感兴趣的:(网络通讯,c语言)