get interface HW address

1. in userspace use ioctl

/*************some error in code***********************/

static int __init getmac_init()
{
        int sock_id;
        struct ifreq ifr;
        char *macstr = "";
        unsigned char *mac = "";

        memset(&ifr,0,sizeof(struct ifreq));
        sock_id = socket(PF_INET, SOCK_STREAM, 0);
        if(sock_id == -1){
                return -1;
        }
        sprintf(ifr.ifr_name,"eth0");

        if(ioctl(sock_id, SIOCGIFHWADDR, &ifr) == 0){
                memcpy(mac,ifr.ifr_hwaddr.sa_data,6);
                sprintf(macstr,"%02X:%02X:%02X:%02X:%02X:%02X",mac[0],mac[1],mac[2],mac[3],mac[4],mac[5]);
        }
        printk("the mac address is:/n %s /n",macstr);

        sock_release(sock_id);

        return 0;
}

/************************************/

 

2.in kernel space use struct net_device

/****************/

#if LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,23)
#define DEV_GET_BY_NAME(name) dev_get_by_name(name);
#else  
#define DEV_GET_BY_NAME(name) dev_get_by_name(&init_net, name);
#endif

 

struct net_device *dev = NULL;

unsigned char *name = "eth0"

dev = DEV_GET_BY_NAME(name);

pirntk("HW address   %02X:%02X:%02X:%02X:%02X:%02X/n",

                                 dev->dev_addr[0],dev->dev_addr[1],dev->dev_addr[2],

                                 dev->dev_addr[3],dev->dev_addr[4],dev->dev_addr[5])

/***************/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值