avatar
Ahmed Zitoun
Blogging about dev, tutorials, life and more
Published on

Pwn The Network - How to spoof your MAC address

How to Change (Spoof) Your MAC Address with Python

A MAC address (Media Access Control address) is a unique hardware identifier assigned to every network device. It plays a critical role in how devices communicate within a local network.

In this article, we’ll cover:

  • What a MAC address is and why it matters
  • Common reasons to spoof (change) a MAC address
  • How to write a Python script that shows, randomizes, or sets a custom MAC address

⚠️ Disclaimer: This tutorial is for educational purposes only. Changing your MAC address to bypass network restrictions or impersonate another device without permission may be illegal. Always test responsibly in your own lab environment.


1. What is a MAC Address?

A MAC address is also known as a physical address or hardware address. It uniquely identifies each device on a local network.

If two devices on the same LAN share the same MAC address, the network will break down because packets cannot be properly delivered.

Architecture of MAC Architecture of MAC

2. Why Spoof a MAC Address?

Changing your MAC address can serve different purposes:

  • Bypass network restrictions: Some Wi-Fi networks filter MAC addresses to allow only approved devices. Spoofing lets you impersonate an authorized device.
  • Privacy protection: If your device has been banned from a network (or logged), spoofing lets you reconnect under a new identity.
  • Security research: MAC spoofing is essential in penetration testing scenarios such as Man-in-the-Middle (MITM) attacks.

3. The Final Product

We’ll build a Python tool that can:

  1. Show the current MAC address of a network interface
  2. Set a random MAC address
  3. Set a custom MAC address of your choosing

First, let’s verify our current MAC address with ifconfig:

Initial ifconfig output

We can achieve the same result using our script, but in a much cleaner way.

MAC show output

Now let's set a random MAC address.

Random MAC change

We can check if we really changed the MAC address of enp0s3 interface using the command ifconfig.

Ifconfig after random change

We can also set a MAC address of our choosing. This can be useful in some situations.

Setting custom MAC

Ifconfig after custom change


4. Let’s Code It

This Python script uses standard libraries (argparse, socket, fcntl, subprocess, random) to manage MAC addresses.

Validate MAC address format

def check_mac(mac):
    pattern = re.compile("\A\w\w:\w\w:\w\w:\w\w:\w\w:\w\w\Z")
    return bool(pattern.match(mac))

Validate network interface

def check_interface(ifname):
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        info = fcntl.ioctl(s.fileno(), 0x8927,
                           struct.pack('256s', bytes(ifname, 'utf-8')[:15]))
        return info
    except OSError:
        return False

Generate a random MAC (LAA format)

A Locally Administered Address (LAA) is a valid MAC address not tied to the vendor.

LAA format Ranges of group and locally administered addresses (Wikipedia)

def generate_random_mac():
    char = "abcdef" + string.digits
    return random.choice(char) + random.choice("26ae") + ":" + \
           "".join(random.choice(char) + random.choice(char) + ":" for _ in range(5))[:-1]

Retrieve current MAC

def getHwAddr(ifname):
    info = check_interface(ifname)
    if info:
        return ':'.join('%02x' % b for b in info[18:24])
    return f"Interface {ifname} does not exist."

Change MAC address

def change_mac(interface, new_mac):
    subprocess.check_output(["sudo","ifconfig",interface,"down"])
    subprocess.check_output(["sudo","ifconfig",interface,"hw","ether",new_mac])
    subprocess.check_output(["sudo","ifconfig",interface,"up"])

Command-line interface

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('--change', action='store_true')
    parser.add_argument('--show', type=str, required=False)
    parser.add_argument('--interface', type=str, required=False)
    parser.add_argument('--fake', type=str, required=False)
    parser.add_argument('--random', action='store_true')
    args = parser.parse_args()

    if args.show:
        print(getHwAddr(args.show))

    if args.change:
        if not args.interface:
            print("Please specify an interface.")
            exit()

        if not (args.fake or args.random):
            print("Please specify --random or --fake <fake_mac>.")
            exit()

        if not check_interface(args.interface):
            print(f"Interface {args.interface} does not exist.")
            exit()

        fake_mac = generate_random_mac() if args.random else args.fake
        change_mac(args.interface, fake_mac)
        print("Current MAC address: ", fake_mac)

if __name__ == "__main__":
    main()

5. Conclusion

MAC addresses are fundamental to network communication, but they can also be manipulated for both legitimate and malicious purposes. In this tutorial, we built a Python script to:

  • Display the current MAC address
  • Randomize the MAC address
  • Set a custom MAC address

This knowledge is a foundation for more advanced attacks and defenses. In the next article, we’ll look at ARP spoofing and how MAC spoofing plays a key role in Man-in-the-Middle attacks.

🔗 Full code: GitHub Repo