🌍 Networking

MAC Address

MAC Address

A 48-bit hardware address that uniquely identifies a NIC. The OUI identifies the manufacturer, ARP maps it to an IP, and beware of spoofing.

📖 Detailed Explanation

MAC Address (Media Access Control Address) is a 48-bit (6-byte) unique hardware address assigned to a network interface card (NIC) at the time of manufacture. Also called a Physical Address or Ethernet address, it uniquely identifies a device at the data link layer (Layer 2) of the OSI model.

A MAC address is usually written in hexadecimal, in the format 00:1A:2B:3C:4D:5E or 00-1A-2B-3C-4D-5E. The first 24 bits (3 bytes) are the OUI (Organizationally Unique Identifier), which the IEEE assigns to the manufacturer, and the last 24 bits are assigned uniquely to each device by the manufacturer. For example, 00:1A:2B indicates the manufacturer Ayecom Technology.

When a data frame is transmitted over an Ethernet or Wi-Fi network, the sender and receiver are identified by MAC addresses rather than IP addresses. ARP (Address Resolution Protocol) translates IP addresses into MAC addresses, enabling communication within the same network. A switch learns a MAC address table and forwards frames only to the appropriate port, which improves network efficiency.

Recently, iOS, Android, and Windows 10/11 have supported a random MAC address (MAC Randomization) feature to protect privacy. They use a different MAC address each time they connect to a Wi-Fi network, which prevents user tracking. On the other hand, MAC spoofing can be abused by attackers to forge their own MAC address in order to bypass network access control or carry out man-in-the-middle (MITM) attacks, so caution is needed from a security standpoint.

💻 Code Example

import uuid
import subprocess
import re

# 현재 장치의 MAC 주소 조회 (내장 모듈)
mac_int = uuid.getnode()
mac_hex = ':'.join(('%012x' % mac_int)[i:i+2] for i in range(0, 12, 2))
print(f"MAC Address: {mac_hex}")  # 예: 00:1a:2b:3c:4d:5e

# getmac 라이브러리 사용 (pip install getmac)
from getmac import get_mac_address

# 로컬 인터페이스의 MAC 주소
local_mac = get_mac_address()
print(f"Local MAC: {local_mac}")

# 특정 인터페이스의 MAC 주소
eth_mac = get_mac_address(interface="eth0")
print(f"eth0 MAC: {eth_mac}")

# 특정 IP의 MAC 주소 (ARP 조회)
remote_mac = get_mac_address(ip="192.168.1.1")
print(f"Gateway MAC: {remote_mac}")

# OUI에서 제조사 정보 추출
def get_vendor_from_oui(mac):
    oui = mac.upper().replace(':', '').replace('-', '')[:6]
    # OUI 데이터베이스 예시 (실제로는 IEEE OUI 파일 참조)
    oui_db = {
        '00505A': 'Apple',
        '00248C': 'Intel',
        '001A2B': 'Ayecom'
    }
    return oui_db.get(oui, 'Unknown Vendor')

print(f"Vendor: {get_vendor_from_oui(mac_hex)}")
# macOS - MAC 주소 조회
ifconfig en0 | grep ether
# 출력: ether 00:1a:2b:3c:4d:5e

# Linux - MAC 주소 조회
ip link show eth0
cat /sys/class/net/eth0/address

# Windows - MAC 주소 조회
ipconfig /all | findstr "Physical"
getmac /v

# ARP 테이블 조회 (IP → MAC 매핑)
arp -a
# 출력: 192.168.1.1 (00:1a:2b:3c:4d:5e) [ether] on eth0

# ARP 캐시 삭제 (Linux)
sudo ip neigh flush all

# 특정 IP의 MAC 주소 조회
arping -c 1 192.168.1.1

# MAC 주소로 제조사 조회 (macOS)
networksetup -listallhardwareports

# MAC 주소 변경 (Linux - 임시)
sudo ip link set dev eth0 down
sudo ip link set dev eth0 address 00:11:22:33:44:55
sudo ip link set dev eth0 up

# MAC 주소 변경 (macOS - 임시)
sudo ifconfig en0 ether 00:11:22:33:44:55

# OUI 조회 (온라인)
curl -s "https://api.macvendors.com/00:1a:2b"
# 출력: Ayecom Technology Co., Ltd.
const os = require('os');

// 모든 네트워크 인터페이스 정보 조회
const interfaces = os.networkInterfaces();

// 각 인터페이스의 MAC 주소 출력
Object.entries(interfaces).forEach(([name, addrs]) => {
    addrs.forEach(addr => {
        if (addr.mac && addr.mac !== '00:00:00:00:00:00') {
            console.log(`${name}: ${addr.mac}`);
        }
    });
});

// 첫 번째 유효한 MAC 주소 가져오기
function getFirstMacAddress() {
    const nets = os.networkInterfaces();
    for (const name of Object.keys(nets)) {
        for (const net of nets[name]) {
            // 내부 루프백이 아닌 것 중 MAC이 있는 것
            if (!net.internal && net.mac !== '00:00:00:00:00:00') {
                return { interface: name, mac: net.mac };
            }
        }
    }
    return null;
}

console.log('Primary MAC:', getFirstMacAddress());

// MAC 주소 형식 검증
function isValidMac(mac) {
    const macRegex = /^([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})$/;
    return macRegex.test(mac);
}

console.log(isValidMac('00:1A:2B:3C:4D:5E'));  // true
console.log(isValidMac('00-1A-2B-3C-4D-5E'));  // true
console.log(isValidMac('invalid-mac'));        // false

// MAC 주소 정규화 (콜론 형식으로 변환)
function normalizeMac(mac) {
    return mac.replace(/[:-]/g, '')
              .match(/.{2}/g)
              .join(':')
              .toLowerCase();
}

console.log(normalizeMac('001A2B3C4D5E'));   // 00:1a:2b:3c:4d:5e
console.log(normalizeMac('00-1A-2B-3C-4D-5E')); // 00:1a:2b:3c:4d:5e

🗣️ Say It Like This in Practice

💬 In a Network Security Meeting
"MAC filtering is good as an additional security layer, but MAC spoofing is easy, so access control should not rely on it alone. It is better to use it together with 802.1X authentication, or to use port security to limit the number of MACs allowed on a specific port."
💬 In an Interview
"A MAC address is a 48-bit hardware address; the first 24 bits identify the manufacturer through the OUI, and the last 24 bits are the device's unique number. ARP maps IP to MAC within the same network, and the switch learns the MAC address table to forward unicast frames efficiently."
💬 During Incident Response
"I checked with arp -a, and the MAC address for the gateway IP has changed to a different MAC rather than the original device. An ARP spoofing attack is suspected, so I will enable Dynamic ARP Inspection and pin the gateway MAC with a static ARP entry."

Take a mock interview on this topic → WIA SOOM AI Interview · Start for free

⚠️ Common Mistakes & Cautions

❌
Relying on MAC filtering alone for security

A MAC address can be easily forged (spoofed). If an attacker knows an allowed MAC, they can change their own MAC to gain access, so be sure to use additional authentication (802.1X, RADIUS) together with it.

❌
Using a MAC address like an IP

A MAC address is valid only on the local network (L2). When a frame passes through a router, its MAC address is changed to that of the next hop. Attempts to track a device by its MAC address in remote communication will fail.

❌
DHCP problems caused by random MAC

When the random MAC feature of iOS/Android is enabled, the same device connects with a different MAC each time, which can cause DHCP address exhaustion or problems with MAC-based access control. In enterprise environments, manage it with MDM.

✅
Correct MAC security configuration

Apply Port Security on the switch to limit the number of MACs, Dynamic ARP Inspection (DAI) to prevent ARP spoofing, and 802.1X to authenticate network access, in combination.

🔗 Related Terms

📚 Learn More