Python узнать mac адрес

Get IP Address, MAC Address and Network Interface Name Using Python : OS Independent

We will make use of Python’s socket module. Here is the brief idea behind my implementation.

  • We will create a socket and instruct it to make use of either IPv4 or IPv6 address and datagram protocol to connect to Google’s DNS server i.e. 8.8.8.8
  • Why Google’s DNS server? Well… it’s always UP or rather we expect it to be always up.
  • Once we connect, then we can retrieve the local address that our socket used to communicate with the DNS server. In this case it will be either your system’s IPv4 or IPv6 address depending on what you have used during the socket creation.

Also please note the following facts before we see the code which gets us the IP address of the machine.

  1. AF_INET is an address family which is used to specify IPv4 i.e. Internet Protocol v4 addresses. Similarly for IPv6 addresses AF_INET6 can be used.
  2. DNS servers use UDP i.e. datagram protocol (WHY? please refer to this post). To connect to a DNS server using a socket you need to use datagram protocol. In python we specify that using SOCK_DGRAM constant.
  3. getsockname() function returns the locally-bound name of the specified socket i.e. the address it has used for connection.
import socket #[Comment]: Gets the IPV4 address of the active network adapter. def get_network_ip_address(self): s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) #[Comment]: 8.8.8.8 is the primary DNS server for Google DNS. It is assumed that this DNS server will always be up. s.connect(("8.8.8.8", 80)) ip = s.getsockname()[0] s.close() return ip

If you need IPv6 address, just replace socket.AF_INET with socket.AF_INET6.

Getting Network Interface Name:

We will make use of Python’s psutil module here. Here is the brief idea behind my implementation.

  • First we will retrieve system’s IPv4 address using the above mentioned technique.
  • We will use ‘psutil‘ module to get all available network interfaces on the system in the form of a list of dictionaries. Each Dictionary contains network interface name as ‘Key‘ and interface details object as ‘Value‘.
  • We will browse through the dictionaries one-by-one and find out which network interface object has a matching IPv4 address (Which we would have already retrieved in the first step).
  • After identifying the network interface just return its name.
import psutil import socket #[Comment]: Gets the active network interface name. def get_active_network_interface_name(self, ipv4Address): nics = psutil.net_if_addrs() netInterfaceName = [i for i in nics for j in nics[i] if j.address==ipv4Address and j.family==socket.AF_INET][0] return netInterfaceName

If you need to search by IPv6 address, just replace socket.AF_INET with socket.AF_INET6.

Getting MAC address:

Here also we will make use of Python’s psutil module. Here is the brief idea behind my implementation.

  • First we will retrieve system’s active network interface name using the above mentioned technique.
  • We will use ‘psutil‘ module to get all available network interfaces on the system in the form of a list of dictionaries.
  • We will browse through the dictionaries one-by-one and get the network interface details object corresponding to the network interface name (Which we would have already retrieved in the first step).
  • After getting the network interface details object just return its MAC address or physical address.
Читайте также:  Python this module reference

Also please note the following fact before we see the code which gets us the MAC address of the machine.

import psutil #[Comment]: Gets the physical/MAC Address of the specified network interface. def get_network_physical_address(self, netInterfaceName): nics = psutil.net_if_addrs() macAddress = ([j.address for i in nics for j in nics[i] if i==netInterfaceName and j.family==psutil.AF_LINK])[0] return macAddress.replace('-',':')

Источник

Get MAC address in python

MAC address stands for Media Access Control address and it is a unique id assigned to hardware components typically to network devices.
These components are called Network Interface Controllers(NIC).
A MAC address is assigned by the manufacturer and cannot be modified. It is also called Ethernet hardware address, hardware address or physical address.

In this article, we will take a look at 2 different ways to determine MAC address in python.

Method 1 : uuid module
Python uuid module has a getnode() method which returns mac address of a hardware.
Remember that a computer has many NIC or network hardwares, so each machine may have many different MAC addresses.

getnode() returns an address of only one of these hardware as a 48 bit integer. Example,

import uuid mac = uuid.getnode() print(mac)

To format it as a hexadecimal value, use hex() function as shown below

import uuid mac = uuid.getnode() print(hex(mac))

If you want a properly formatted address as visible in terminal or command prompt, as a 12 digit value separated into blocks of 2 digits each and separated by a colon(:), use below code

import uuid import re print (':'.join(re.findall('..', '%012x' % mac)))

To understand the above code, break it into parts as below

import uuid import re mac= hex(uuid.getnode()) # remove 0x mac=mac.replace('0x','') # break into 2 digit list mac=re.findall('..', mac) # add : separator print(':'.join(mac))

1. Determine mac address with getnode() and convert it to a hex string with hex() function.
2. Remove leading 0x from it using replace() function.
3. Break the resulting string into 2 digit values using findall() function from re module.
findall() returns a list of values.
4. Combine the elements of this list with : as separator using python string join() function .

Output of this code will be

Method 2 : Using getmac module
Another method to get MAC address in python is using a third party package getmac .
It provides get_mac_address() function which returns MAC address. Example,

import getmac mac = getmac.get_mac_address() print(mac)

You can directly import this function as a shorter alias. This makes invoking it easier when required at multiple places. Example,

from getmac import get_mac_address as gmac mac = gmac()

As stated earlier, a single machine has multiple NICs installed.
With get_mac_address() function, you can get the MAC address of a hardware using its name.
It also enables you to find MAC address of a particular ip as shown below.

from getmac import get_mac_address as gmac eth_mac = gmac(interface="eth0") ip_mac = gmac(ip="127.0.0.1") host_mac = gmac(hostname="localhost")

Replace the hardware names as per the system on which you are running this program.

To install getmac package using pip, use below command

Hope that article was useful.

Python

  • Introduction
  • Set up
  • First Program
  • Variables
  • Printing Output
  • User Input
  • if statement
  • Loops
  • String
  • List
  • List comprehension
  • List slicing
  • Tuple
  • Dictionary
  • Iterate dictionary
  • Functions
  • Exception handling
  • File handling
  • Modules
  • Generators: Generator expression and function
  • map() function
  • filter() function
  • enumerate() function
  • Lambda function
  • Check data type of variable in python
  • Advanced
  • Programming Examples

Источник

How to get MAC address of a device in Python

In this tutorial, we will write a Python program using a special module called UUID to fetch your system’s MAC address. This module is particularly used to fetch the MAC address of any system. A media access control address is a distinctive identifier of a system that helps two or more devices connect, especially when on the same local network.

To get the MAC address of a device in Python, you can use the getnode function in the uuid module. This function generates a unique MAC address based on the system’s hardware information.

import uuid mac_address = uuid.getnode() print(mac_address)

The getnode function returns the MAC address as an integer. If you want to print it in the traditional MAC address format (e.g., 00:11:22:33:44:55 ), you can use the hex function to convert the integer to a hexadecimal string, and then use string formatting to insert the colons:

import uuid mac_address = uuid.getnode() mac_address_hex = ':'.join([''.format((mac_address >> elements) & 0xff) for elements in range(0,8*6,8)][::-1]) print(mac_address_hex)

Keep in mind that this method only works for the device running the Python script. If you want to get the MAC address of a different device on the same network, you will need to use a different method such as using the arp command or sending a network packet to the device and reading the MAC address from the response.

Get MAC address of a different device in Python

To use the arp command to get the MAC address of a device in Python, you can use the subprocess module to call the arp command and capture the output.

Here is an example of how to do this:

import subprocess def get_mac_address(ip_address): arp_command = ['arp', '-n', ip_address] output = subprocess.check_output(arp_command).decode() mac_address = output.split()[3] return mac_address mac_address = get_mac_address('192.168.1.1') print(mac_address)

This code will call the arp command with the -n flag, which displays the ARP table with IP addresses and MAC addresses, and the IP address of the device you want to get the MAC address for. The output will be a string containing the ARP table, and the MAC address will be the fourth item in the list of words obtained by splitting the output string on whitespace.

Keep in mind that this method only works if the device you are trying to get the MAC address for is on the same network as the device running the Python script, and if the arp command is available on the system. The arp command may not work if the device has privacy settings enabled that prevent it from responding to ARP requests.

Example 1: MAC address in integer format in Python

# import the essential modules from uuid import getnode as get_mac # get the mac address mac=get_mac() # print the mac address print("the mac address is:",mac)

For security purposes, the mac address cannot be disclosed. In this way, you can very easily figure out the MAC address of your device but this method will print a very complex MAC address. So, to reduce the complexity you can use the program given below.

Example 2: Get traditional MAC address format in Python

For reducing the complexity of the MAC address we have to convert it into the hexa format as shown in this code.

# import the essential modules from uuid import getnode as get_mac # get the mac address mac=get_mac() # print the mac address print("the mac address is:",mac) # covert it into hexa format print(hex(mac)) # reduce the complexity # macstring performs the clearest form of mac address and it is the correct form of valid address # here the for loop arranges the valid mac address in orderly formats macString=':'.join(("%012X" % mac) [i:i+2] for i in range(0,12,2)) # now print the valid mac address in the correct format print('[' + macString + ']')

For security reasons, the MAC address cannot be exposed. So, this way you can fetch the MAC address of your computer system.

Источник

Оцените статью