Linux内核 获取本机mac,linux 获取本机MAC/IP地址的方法

功能:查询本机IP/MAC地址,过滤掉127.0.0.1 loop-back 地址

适用:linux, ubuntu 16.04 调试通过

#include

#include

#include

#include

#include

#include

#include

#include

#include

#include

#include

#include

#include

#include

#include

void getLocalMacIp()

{

int i;

int sock_mac;

char hname[128];

struct hostent *hent;

struct in_addr *paddr = 0;

struct ifaddrs * ifAddrStruct=NULL;

struct ifreq ifr_mac;

void * tmpAddrPtr=NULL;

struct ifreq buf[16];

struct ifconf ifc;

int interface_num;

char nif_name[128] = {0};

char addressBuffer[128];

unsigned char macaddr[6] = {0};

unsigned char *pFirstByte;

//---------------------------------------------

//get device IP address, discard loopback

//---------------------------------------------

gethostname(hname, sizeof(hname));

hent = gethostbyname(hname);

printf("[%s][%d] host: %s\n", __FILE__, __LINE__, hent->h_name);

getifaddrs(&ifAddrStruct);

while (ifAddrStruct!=NULL)

{

if (ifAddrStruct->ifa_addr->sa_family==AF_INET)

{

tmpAddrPtr = &((struct sockaddr_in *)ifAddrStruct->ifa_addr)->sin_addr;

pFirstByte = (unsigned char*)tmpAddrPtr;

if(*pFirstByte != 127)

{

paddr = tmpAddrPtr;

inet_ntop(AF_INET, tmpAddrPtr, addressBuffer, 128);

printf("[%s][%d] NIF %s address %s\n", __FILE__, __LINE__,

ifAddrStruct->ifa_name, addressBuffer);

//---------------------------------------------

//remember NIF name for future use

//---------------------------------------------

strcpy(nif_name, ifAddrStruct->ifa_name);

}

}

ifAddrStruct=ifAddrStruct->ifa_next;

}

//---------------------------------------------

//get device MAC address, discard loopback

//---------------------------------------------

sock_mac = socket( AF_INET, SOCK_DGRAM, 0 );

if(sock_mac > 0)

{

ifc.ifc_len = sizeof(buf);

ifc.ifc_req = buf;

ioctl(sock_mac, SIOCGIFCONF, (char *)&ifc);

interface_num = ifc.ifc_len / sizeof(struct ifreq);

while(interface_num--)

{

if(nif_name[0] && strcmp(nif_name, buf[interface_num].ifr_name))

{

continue;

}

ioctl(sock_mac, SIOCGIFHWADDR, (char *)&buf[interface_num]);

memcpy(macaddr, &buf[interface_num].ifr_hwaddr.sa_data[0], 6);

//printf("NIF %s ", buf[interface_num].ifr_name);

//printf("mac %02x:%02x:%02x:%02x:%02x:%02x \n",

//    macaddr[0], macaddr[1], macaddr[2], macaddr[3], macaddr[4], macaddr[5]);

}

close( sock_mac );

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值