sha*_*ggy 5 c linux mac-address ip-address
可能重复:
Linux/C++:获取本地计算机的IP地址
我试图获取本地计算机的所有接口的IP和MAC地址,但我不能真正成功.我需要把它放在一起,所以我知道哪个IP属于哪个MAC.
我在google上进行了很多搜索,甚至在这里,但是我找不到真正的C代码.
请你帮助我好吗?
提前致谢!我真的很感激!
在相对较新版本的Linux上,您只需读取/sys/class/net/eth0/address(替换任何网络接口名称eth0)的内容即可获取接口的硬件地址.
刚发现这个工作:
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <net/if.h>
#include <stdio.h>
#include <string.h>
void mac_eth0(unsigned char MAC_str[13])
{
#define HWADDR_len 6
int s,i;
struct ifreq ifr;
s = socket(AF_INET, SOCK_DGRAM, 0);
strcpy(ifr.ifr_name, "eth0");
ioctl(s, SIOCGIFHWADDR, &ifr);
for (i=0; i<HWADDR_len; i++)
sprintf(&MAC_str[i*2],"%02X",((unsigned char*)ifr.ifr_hwaddr.sa_data)[i]);
MAC_str[12]='\0';
close(s);
}
int main(int argc, char *argv[])
{
unsigned char mac[13];
mac_eth0(mac);
puts(mac);
return 0;
}
Run Code Online (Sandbox Code Playgroud)