Linux 如何获取本地IP和MAC地址C

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6767296/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-05 05:10:02  来源:igfitidea点击:

How to get local IP and MAC address C

clinuxip-addressmac-address

提问by shaggy

Possible Duplicate:
Linux / C++: Get the IP Address of local computer

可能的重复:
Linux / C++:获取本地计算机的 IP 地址

I am trying to get my local computer's IP and MACaddresses of all interfaces, but I can not really succeed. I need to get it together, so I know which IP belongs to which MAC.

我正在尝试获取所有接口的本地计算机的IP 和 MAC地址,但我无法真正成功。我需要把它放在一起,所以我知道哪个IP属于哪个MAC。

I went through a lot of searching on google and even here, but I can not really find a C codefor this.

我在谷歌甚至这里进行了大量搜索,但我无法真正找到用于此的C 代码

Could you please help me?

请你帮助我好吗?

Thanks in advance! I would really appreciate that!

提前致谢!我真的很感激!

回答by Aaditi Sharma

On your local computer? Since it is tagged under linux, open a terminal, and type ifconfig -a. That displays all the info on all interfaces On your local network, your IP is listed under inet address.The HWaddr is the MAC address. For external IP, you'll have to use a script to fetch it.

在您的本地计算机上?因为它是在 linux 下标记的,所以打开一个终端,然后输入 ifconfig -a。这会显示所有接口的所有信息 在您的本地网络上,您的 IP 列在 inet 地址下。 HWaddr 是 MAC 地址。对于外部 IP,您必须使用脚本来获取它。

EDIT : Click Herefor using it for a C Program

编辑:单击此处将其用于 C 程序

回答by kcbanner

You can get the MAC address using the SIOCGIFADDR ioctl.

您可以使用 SIOCGIFADDR ioctl获取 MAC 地址。

A full example can be found here.

一个完整的例子可以在这里找到。

回答by Friek

Just found this to be working:

刚刚发现这是有效的:

#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]='##代码##';
    close(s);
}

int main(int argc, char *argv[])
{
    unsigned char mac[13];

    mac_eth0(mac);
    puts(mac);

    return 0;
}

回答by bitbucket

On relatively recent versions of Linux, you can just read the contents of /sys/class/net/eth0/address(substituting any network interface name for eth0) to get the hardware address of an interface.

在相对较新的 Linux 版本上,您只需读取/sys/class/net/eth0/address(用任何网络接口名称替换eth0)的内容即可获得接口的硬件地址。