Linux network mac address

Get network interface name and MAC address on command line

Interestingly, you can also do it by ifconfig | grep HW | awk ‘< print $1" : "$5 >‘ . Since loopback doesn’t have a HW address, grep will ignore lo .

8 Answers 8

You can get the MAC address from /sys/class/net//address :

$ cat /sys/class/net/enp0s3/address 08:00:27:15:dc:fd 
find /sys/class/net -mindepth 1 -maxdepth 1 ! -name lo -printf "%P: " -execdir cat <>/address \; 
enp0s3: 08:00:27:15:dc:fd docker0: 02:42:61:cb:85:33 

Or, using ip ‘s one-line mode, which is convenient for scripting:

$ ip -o link | awk '$2 != "lo:" ' enp0s3: 08:00:27:15:dc:fd docker0: 02:42:61:cb:85:33 

The /sys directory has been a feature of the Linux kernel since before version 2.6 and as such should be available on all distributions.

ip -o link | grep ether | awk '< print $2" : "$17 >' 
  • where -o gives on-line result for every interface.
  • grep ether filters out only those interface that have a Ethernet address assigned to it.
  • And awk simply prints the 2nd & 17th column from the lines with a colon in between.
ip -br link | grep -v LOOPBACK | awk '< print $1 " : " $3 >' 
  • -br gives the brief information of interfaces.
  • grep -v LOOPBACK ignores the word LOOPBACK that is present only in lo interface.
  • And awk prints first & 3rd column.

Using ifconfig

where grep HW filters out only those interface that have a hardware address assigned to it.

The Hack

grep HW or grep ether actually ignores the lo because

With no arguments xargs will replace all newlines, tabs and multiple spaces to single space. By adding -n 2 it will slice that line after each second word. So:

I made an ugly hacky one liner:

 ip link | awk -F' ' '' | paste -d " " - - | grep -v lo: 

If you count the fields using space as separators you will see the fields you need are the 2nd and 17th.

But they will be printed one under the other, the paste places the adjacent lines as colums. The paste fix that placing adjacent lines side by side in a line. I could not find a smart way to avoid getting the lo line so I just excluded it before printing with grep

ip link | awk -F' ' '' | paste -d " " - - | grep -v lo: enp2s0: 50:9a:4c:b5:af:ea wlp3s0: e8:9e:b4:66:e3:ea 

Источник

How to Find Network MAC Address in Linux System

The term MAC Address is a derived abbreviation for Media Access Control Address. The network interface controller (NIC) uses the MAC address as its assigned unique identifier within an existing network segment.

Читайте также:  Изменить настройки пользователя linux

To practically relate to or understand what a MAC address is, think of it as the postal or physical address to a house. The house in this case is the network interface controller (NIC).

There is a key difference between MAC address and IP address and therefore we should not confuse the two. MAC address identifies the device you are using since it is imprinted on the device hardware whereas IP address identifies the connection status among devices seeking to communicate on an existing/configured network.

The MAC address of any device is represented by a 12-digit hexadecimal number. Its display includes a colon or hyphen after every two MAC address digits for easy readability.

For instance, a MAC address can be represented in the following manner.

aa:bb:cc:dd:ee:ff or gg-hh-ii-jj-kk-ll

Approaches to Finding MAC Address in Linux

Depending on the number of network interfaces on your Linux machine like Wi-Fi built-in and Ethernet port, your computer can be associated with more than one MAC Address.

1. Find Linux System Mac Address Using IP Command

The ip command is part of the iproute2 package and can be used to display both the MAC address and IP address of your Linux-powered machine using either of the following commands.

$ ip addr or $ ip address or $ ip address show

Find Linux System MAC Address

Depending on the network adapter or interface present, we can see the availed MAC addresses. In the above screen capture, three distinct MAC addresses can be identified from the ip address command.

Another useful command is the ip link which only focuses on the MAC address and does not display the IP addresses.

Show Linux System MAC Address

2. Find Linux System Mac Address Using Ifconfig Command

The ifconfig command is another effective approach to identifying the MAC address of your Linux machine. We however need to install it first since it is a member of the net-tools package and not installed on Linux by default.

$ sudo apt install net-tools [On Debian, Ubuntu and Mint] $ sudo yum install net-tools [On RHEL/CentOS/Fedora and Rocky Linux/AlmaLinux] $ sudo emerge -a sys-apps/net-tools [On Gentoo Linux] $ sudo pacman -S net-tools [On Arch Linux] $ sudo zypper install net-tools [On OpenSUSE]

Once installed, run the ifconfig command to find the IP address and MAC address of your Linux system.

Check Linux System MAC Address

Different network interfaces or adapters showcase different MAC addresses as highlighted in the above screen capture.

We have successfully defined and understood how to get the MAC address(es) on our Linux machines.

Источник

Как узнать MAC-адрес в Linux

В те времена, когда только проектировался Ethernet, предусматривалось применение уникального номера каждой сетевой карте, подключённой к нему. Назначался он при изготовлении платы. MAC-адрес используется для определения получателя и отправителя информации в Сети. И в этой статье речь пойдёт о том, как узнать MAC адрес в Linux.

Читайте также:  Linux all users in network

Практически во всех операционных системах на основе ядра Linux используется две консольные утилиты, с помощью которых можно узнать аппаратный адрес карты: ifconfig и ip. Различные графические приложения этого типа используют их данные.

Как узнать MAC-адрес с помощью ifconfig

Одной из первых сетевых программ в истории Linux является ifconfig. В некоторых дистрибутивах она запускается только от имени администратора, а где-то вообще не установлена. Рассмотрим её инсталляцию и использование в Manjaro Linux.

Пакет, содержащий в себе некоторые сетевые утилиты (в том числе и ifconfig), в Manjaro- и Arch-подобных системах называется net-tools. Установим его.

А в Ubuntu- и Debian-подобных системах:

sudo apt install net-tools

Чтобы узнать MAC-адрес Linux, сначала смотрим список интерфейсов:

ifconfig -a

Доступных интерфейсов два: enp0s7 (в вашем случае он может называться по другому) и lo (он же локальный хост, который одинаков практически для всех компьютеров). Нам нужен enp0s7.

MAC-адрес устройства виден уже сейчас в поле ether, но чтобы отобразить только его, воспользуемся такой командой:

ifconfig -a | grep ether | gawk »

MAC

Здесь grep принимает на вход то, что вывела команда ifconfig -a, находит строку, где есть ether, и передаёт на вход команде gawk, которая выбирает второе слово в принятой строке.

Как посмотреть MAC-адрес с помощью ip

Более новой в системах GNU/Linux (относительно ifconfig) является программа ip. Её принцип работы практически такой же. Отличается синтаксисом и выводимой информацией. И она установлена по умолчанию для всех систем. Для отображения сетевых интерфейсов нужно ввести команду:

ip -a

Здесь lo и enp0s7 расположены в обратном порядке.

Чтобы узнать MAC адрес сетевой карты Linux, вводим ту же самую конструкцию, только для этой команды:

ip MAC

Выводы

За то, как узнать MAC адрес в Linux, отвечают две консольные утилиты — ifconfig и ip. Первая может запускаться от имени администратора в некоторых дистрибутивах (например в Debian), а где-то вообще не быть установленной (Manjaro). Это связано с её отходом на второй план, поскольку ip является более новой программой и устанавливается по умолчанию во всех системах.

Обнаружили ошибку в тексте? Сообщите мне об этом. Выделите текст с ошибкой и нажмите Ctrl+Enter.

Источник

How to Look Up MAC Addresses

The MAC address, also known as Media Access Control address, is a unique and separate hardware number of a particular computer, especially in a LAN (Local area network) or in other networks. When you are connected to the Internet as a host or your computer is connected to the Internet, the IP address of your computer is linked to the physical MAC address of the computer on a LAN. The MAC address is the same as the Ethernet address on the Ethernet LAN. In telecommunication protocols, the media access control, which is the sublayer of the data-link layer, uses the MAC address. For each type of device, there is a different MAC sublayer. In the DLC layer, the other sublayer is a logical link control sublayer.

Next, we will show you how to find the IP and MAC addresses of a device with the help of the command-line in Linux.

Читайте также:  Kernel panic linux mint

Finding IP and MAC Address Using the Command-Line

With the help of the IP command, you can find both the IP and MAC address of your network connection. Here, we will discuss the networking command IP in Linux. The network parameters of Linux are useful to withdraw by using this command. This command will work on different Linux systems, such as Kali Linux, Arch Linux, Fedora, Ubuntu, etc.

The IP command

The IP command replaces the ifconfig command, which is part of the net-tools package. The IP command is very strong and powerful. The syntax of the IP command is written as follows:

In the above command, the xx will be replaced by the following two to obtain the preferred result. These operators include:
-s, which is used to show more information related to the command
-V, which is used to show the ip utility version

To check IP address in Kali Linux, enter the ifconfig command, as shown below:

Finding the IP Address of a Linux System

To list each of the IP addresses of a system, write the following command in the terminal:

This command will display all the IP addresses with their device names that are currently available. If someone does not like the default IP address connected to the internet, then they can use a grep parameter. The parameter can be written as shown below:

Another option is to use the device name, but in this case, it is essential to use the names of the particular network devices. To do this, enter the following command:

Here, you will see that the Ethernet connection is eth0, while wlp2s0 represents the wireless connection. We will use the eth0 in this example:

Finding the MAC Address of a Linux System

Any network device has a critical parameter, such as a MAC address, that will also include the hardware of the computer or a server. There is a unique MAC address for each device on the network that is connected to the computer.

Enter the ip link command into the terminal, as shown below:

The ip link utility lists several parameters for a device. There are two lines for each of the devices for the link-state and their properties. The first line will show the current state of the particular device, the maximum transmission unit, a set of flags on the device, etc. Similarly, the second line will indicate the current MAC address or the type of link layer currently in use. The previous example found the MAC addresses of the two LAN connections currently in use.

Conclusion

This tutorial showed you how to look up MAC addresses in Linux. The commands in this article work with many distros, including Kali, Arch, and Ubuntu Linux machines.

About the author

Younis Said

I am a freelancing software project developer, a software engineering graduate and a content writer. I love working with Linux and open-source software.

Источник

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