Skip to main content

how to get mac address using python socket

Namaste Friends,



Introduction


In this post, I am going to tell you about how we can easily get the address of our interface using python socket module. Actually, To retrieve the mac address of our card here we going to use python socket module sock name function.

Sock name function returns socket information as a tuple. so, to get the mac address of your interface card, first, we need to create a dummy socket object and then, bind it with the specific interface. basically, specific interface means the interface whose address you want to find.

Example Code


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
import socket
from binascii import hexlify

# get mac address
def get_mac(interface, p=0):

    # create dummy socket
    s = socket.socket(socket.AF_PACKET, socket.SOCK_RAW)

    # bind it with interface name
    s.bind((interface,p))

    # extract mac address
    mac =  hexlify(s.getsockname()[4])

    # close socket
    s.close()

    #return value
    return mac

Explanation


  • line 8, To create a dummy socket object.
  • line 11, Bind socket with interface card.
  • line 14, extract mac address from tuple
  • line 17, close socket




Related Post

Top Visited

Big List Of Google Dorks For Sqli Injection

how to install burp suite in Linux/Ubuntu 16.04

Create Simple Packet Sniffer Using Python

Create Ping Sweeping Script Using Python

Python Beautiful Soup Module - Tutorial - Part 2

how to configure burpsuite with firefox?

Latest Google Dorks List

List of Keyboard Shortcuts Keys for GNOME Desktop (Kali linux / Linux / Ubuntu/*nix )

What is Burp Suite And its Features?

What is the use of Pseudo header in TCP/UDP packets?