📜  获取设备的 Mac 地址 (1)

📅  最后修改于: 2023-12-03 15:41:30.767000             🧑  作者: Mango

获取设备的 MAC 地址

MAC 地址是用于识别网络设备的物理地址。在一些应用场景下,需要获取设备的 MAC 地址来进行设备识别或者是安全检查,本文将介绍几种常见的获取设备 MAC 地址的方法。

1. 使用系统命令

在 Linux、Unix、macOS 等系统上,可以使用 ifconfig 或者 ip 命令来获取设备的 MAC 地址。在 Windows 系统上,可以使用 ipconfig /all 命令。

示例代码:

# Linux、Unix、macOS
ifconfig en0 | grep ether | awk '{print $2}'

# Windows
ipconfig /all | findstr "Physical Address"

返回值示例:

00:11:22:33:44:55

注意:不同系统的命令和输出格式可能略有不同,需要根据具体系统和输出进行解析。

2. 使用 Python 代码

使用 Python 中的 uuidsocket 或者 netifaces 模块来获取设备的 MAC 地址。

示例代码:

# 使用 uuid 模块
import uuid

print(uuid.getnode())

# 使用 socket 模块
import socket

print(':'.join(['{:02x}'.format((uuid.getnode() >> ele) & 0xff) for ele in range(0, 8 * 6, 8)][::-1]))

# 使用 netifaces 模块
import netifaces as ni

print(ni.ifaddresses('en0')[ni.AF_LINK][0]['addr'])

返回值示例:

12345678901234
00:11:22:33:44:55
00:11:22:33:44:55

注意:使用 uuid.getnode() 方法获取的 MAC 地址可能与硬件实际地址有所差异,需要进行位移和格式化处理。

3. 使用 Java 代码

使用 Java 中的 NetworkInterface 类来获取设备的 MAC 地址。

示例代码:

import java.net.NetworkInterface;
import java.util.Arrays;

NetworkInterface networkInterface = NetworkInterface.getByName("en0");
byte[] mac = networkInterface.getHardwareAddress();
System.out.println(Arrays.toString(mac));

返回值示例:

[0, 17, 34, 51, 68, 85]

注意:返回值为 byte 数组,需要进行格式化输出。

4. 使用 C 语言代码

使用 C 语言中的 getifaddrs 函数来获取设备的 MAC 地址。

示例代码:

#include <stdlib.h>
#include <stdio.h>
#include <ifaddrs.h>
#include <netinet/in.h>
#include <net/if.h>
#include <string.h>

int main() {
    struct ifaddrs *ifaddr, *ifa;
    int family, s;
    char host[NI_MAXHOST];

    if (getifaddrs(&ifaddr) == -1) {
        perror("getifaddrs");
        exit(EXIT_FAILURE);
    }

    for (ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next) {
        if (ifa->ifa_addr == NULL)
            continue;

        family = ifa->ifa_addr->sa_family;

        if (family == AF_LINK) {
            struct sockaddr_dl *sdl = (struct sockaddr_dl*) ifa->ifa_addr;
            int dl_len = sdl->sdl_alen;
            char mac[dl_len];

            if ((s = getnameinfo(ifa->ifa_addr,
                                 sizeof(struct sockaddr_dl),
                                 host, NI_MAXHOST, NULL, 0, NI_NUMERICHOST)) == 0) {
                memcpy(mac, LLADDR(sdl), dl_len);
                printf("%s MAC Address: %02x:%02x:%02x:%02x:%02x:%02x\n",
                       ifa->ifa_name,
                       mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
            }
        }
    }

    freeifaddrs(ifaddr);
    return 0;
}

返回值示例:

en0 MAC Address: 00:11:22:33:44:55

注意:需要引入系统头文件,返回值为字符数组,需要进行格式化输出。