Как посмотреть mac адрес ubuntu
Перейти к содержимому

Как посмотреть mac адрес ubuntu

  • автор:

How to List/Get/Display/Find MAC Address in Linux Using 11 Popular Methods

In this article, I will take you through different ways to List/Get/Display/Find MAC Address in Linux. You might be aware of Ethernet Card/Network Card/NIC Controller which works at Network level and is responsible for communicating with other network devices in a Network Topology. It is used in Layer-2 Communication. You can find the usage of MAC address in wide range of Network Devices currently in use. This is typically in-line with IEEE 802 Network technologies.

What is MAC Address

MAC is abbreviated as Media Access Control. It is a unique 48 bit(6-byte) address assigned to a Network Interface. It is almost used in all the Network Devices which has network controller in it. It will always show in this form 00:07:Y7:1C:6L:03.

How to List/Get/Display/Find MAC Address in Linux Using 11 Popular Methods 1

Find MAC Address in Linux

Method 1: How to find MAC Address in Linux Using ifconfig command

If you want to check MAC Address of all the network interfaces in Linux using our traditional ifconfig command then you need to use ifconfig -a command as shown below.

Method 2: How to find an ethernet MAC Address in Linux Using ifconfig command

If you want to check the MAC Address of a specific network interface using ifconfig command then you need to use network interface name with ifconfig command as shown below. Here we are checking MAC Address of interface enp0s3 using ifconfig enp0s3 command.

Method 3: How to find MAC Address in Linux Using ip addr sh command

If you want to check the MAC address of all the network interfaces then you need to simply use ip addr sh command and check the MAC address from ether field as shown below.

Method 4: How to find an ethernet MAC Address in Linux using ip addr sh command

If you want to check the MAC address of some specific network interface then you need to use the interface name with ip addr sh command and check the MAC address from ether field as shown below. In this example we are checking MAC address of enp0s3 network interface.

Method 5: How to find MAC Address in Linux Using ip link show command

If you want to check the MAC address of all the network interfaces then you can use another useful ip link show command and check the MAC address from link/ether field as shown below.

Method 6: How to find an ethernet MAC Address in Linux using ip link show command

If you want to check the MAC address of some specific network interface then you need to use the interface name with ip link show command and check the MAC address from ether field as shown below. In this example we are checking MAC address of enp0s3 network interface.

Method 7: How to find MAC Address in Linux using ethtool command

You can also use another useful linux tool called ethtool to find MAC address in Linux as shown below. Here I am checking MAC address of my ethernet card enp0s3 using ethtool command hence you need to mention your Interface name before running below command.

Method 8: How to find MAC Address in Linux using Regex with ifconfig command

You can use a simple grep regular expression with ifconfig command to find the MAC Address of an ethernet card in Linux as shown below. Like above example, Here I am using regular expression on my System enp0s3 interface so you need to change and mention your interface name instead of enp0s3 before running below command.

Method 9: How to find MAC Address in Linux using SYS Files

If you want to check MAC address in Linux using SYS files you need to check network address file using below cat command. As mentioned below SYS file is a text file so its contents can always be seen through Linux cat command.

Method 10: How to find MAC Address in Linux using AWK Regex with ifconfig command

You can also use AWK regular expression with ifconfig command to find MAC Address in Linux as shown below. Here we are grepping ether keyword from ifconfig command and then piping to awk to get first and second column output separated by tab.

Method 11: How to find MAC Address in Linux using Sed Regex with ifconfig command

Like above example, you can also use Sed Regular expressions with ifconfig command to find MAC Address in Linux as shown below.

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

Данная статья поможет разобраться в том, как узнать MAC-адрес компьютера или любого другого сетевого устройства, работающего под управлением различных операционных систем (Windows, Linux, Android и другие).

Что такое MAC-адрес и зачем он нужен

MAC-адрес — это уникальный идентификатор сетевой карты (интерфейса) или беспроводного адаптера. MAC также называют физическим адресом (Hardware Address) компьютера, ноутбука, роутера, смартфона, другими словами — любого устройства, работающего, в частности, в сетях Ethernet. Именно стандартом Ethernet предусмотрено использование уникального значения MAC-адреса, состоящего из шести байт информации, для каждого сетевого устройства.

Интересный факт. Уникальность физических адресов достигается за счет обращения производителей сетевых карт к контролирующему органу, именуемому IEEE Registration Authority, который, свою очередь, выделяет им пул адресов (больше 16 миллионов значений) для назначения новым устройствам.

По мере использования полученного диапазона, производитель может обратиться в IEEE повторно, так сказать, за «добавкой».

В широковещательных сетях (например таких, как Ethernet) физический адрес дает возможность определить каждый узел (компьютер) сети и доставлять данные исключительно ему. Именно MAC-адреса формируют некую основу сетей на канальном уровне – составляющей модели OSI.

Процесс определения физического адреса для разных типов устройств и операционных систем немного отличается, но все равно остается довольно простым занятием.

Самый легкий способ узнать MAC-адрес компьютера — найти соответствующую информацию на коробке вашего ноутбука/роутера/смартфона (нужное подчеркнуть!) и так далее.

Но, если этот способ не для вас, а коробка была успешно выброшена, или вариант с походом к антресолям — это вовсе не вариант, пожалуйста, продолжайте чтение этой статьи.

Определяем MAC-адрес в Windows

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

Для того, чтобы узнать MAC-адрес компьютера в Windows, можно воспользоваться тремя основными способами. Ни один из них не требует установки дополнительных программ или утилит, позволяя обойтись лишь внутренними возможностями «окон».

Способ 1. Узнаем MAC-адрес через командную строку

Командная строка Windows – обязательный инструмент для каждого пользователя из разряда «уверенных». Использование CMD (от англ. command prompt) в определении физического адреса устройства является универсальным и подходит для любой версии популярной операционной системы Microsoft (будь то проверенные временем Windows 7 или Windows 8, новенькая Windows 10 или старая добрая Windows XP).

Для того, чтобы открыть командную строку, необходимо воспользоваться одним из многочисленных вариантов. Мы выделим из них два наиболее удобных:

  1. Одновременно нажмите клавишу Win (кнопка с «окнами» в нижнем левом углу клавиатуры) и клавишу X (икс), после чего появится контекстное меню, в котором следует кликнуть по пункту «Командная строка»

Открытие командной строки через Win+X

  1. Одновременно нажмите клавишу Win и клавишу R, после чего появится окно «Выполнить». Введите слово cmd в поле и нажмите ОК.

Вход в CMD через Выполнить

После доступа к командной строке можно опять же поступить двумя способами, точнее — воспользоваться двумя командами:

  • ipconfig /all — покажет детальную информацию обо всех физических и виртуальных сетевых устройствах, используемых в компьютере. В моем случае система определила сразу два MAC-адреса: физический адрес стандартного Ethernet-порта (для сетевого кабеля) и Wi-Fi адаптера, который используется для доступа к сети (не люблю я все эти кабели, знаете ли!). Обратите внимание, что, помимо информации о MAC-адресе, для Wi-Fi адаптера присутствуют другие сетевые данные (IP-адрес, адрес шлюза, DNS серверы и так далее).

Результат команды ipconfig

  • getmac — покажет информацию о MAC-адресе для всех физических устройств компьютера. По моему скромному мнению является предпочтительной, потому что не усложняет жизнь пользователю лишней информацией.

Команда getmac

Используя дополнительные атрибуты для команды getmac ( /v или /fo list ) вы получите информацию в развернутом виде.

Команда getmac с атрибутами

Что ж, теперь вы знаете, как узнать MAC-адрес компьютера через командную строку!

Способ 2. Ищем MAC-адрес в сведениях о системе

Для получения доступа к сведениям об операционной системе необходимо воспользоваться уже известным вам инструментом «Выполнить» (комбинация клавиш Win + R), после чего ввести в поле msinfo32 как показано на рисунке и нажать «ОК».

Как узнать информацию о системе

В левой части появившегося окна развернуть пункт «Компоненты» (нажатием «плюсика» или двойным щелчком), выбрать «Сеть», далее «Адаптер», и в правой части окна отыскать графу «MAC-адрес».

Узнать MAC-адрес в сведениях о системе

Вуаля! Просто, не правда ли?

Способ 3. Определяем MAC-адрес в сетевых подключениях

Для доступа к списку сетевых подключений воспользуемся все той же комбинацией Win + R (команда ncpa.cpl):

Команда ncpa

В открывшемся окне находим наше активное сетевое подключение и открываем его свойства (правый клик по иконке):

Свойства сетевого подключения

Затем наводим курсор мыши название используемого адаптера и получаем его MAC-адрес в виде всплывающего текста!

MAC-адрес в свойствах сетевого подключения

Пожалуй, главный минус данного способа — невозможность скопировать полученное значение для дальнейшего использования. Да и быстрым этот способ узнать MAC-адрес компьютера назвать нельзя.

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

Для того, чтобы узнать MAC-адрес сетевого интерфейса в операционной системе семейства Linux воспользуйтесь командой ifconfig (или sudo ifconfig ) в вашем любимом терминале. Искомый результат будет находиться рядом со словом HWaddr:

В ОС Linux вопрос определения физического адреса также можно решить с помощью команды ip (или sudo ip ):

Физический адрес в Apple Mac OS

Счастливые обладатели Apple могут воспользоваться терминалом (команда ifconfig ) для того, чтобы узнать физический адрес компьютера:

Или же, не углубляясь в тонкости системы, перейти в «Системные настройки», затем «Сеть», после чего обратиться к расширенным настройкам и выбрать интересующий адаптер: Ethernet (проводной) или AirPort (Wi-Fi). MAC-адрес проводного интерфейса будет расположен во вкладке «Оборудование», беспроводного — в графе AirPort ID.

Где посмотреть MAC-адрес смартфона или планшета

Android

Методика определения MAC-адреса для устройств на базе операционной системы Android если не одинакова для всех устройств, то уж точно очень похожа. Ниже приведен пример того, как узнать MAC-адрес на андроиде (на примере телефона Meizu M3 Note).

Для этого заходим в «Настройки», далее в меню управления беспроводными сетями «WLAN», переходим в «Расширенные настройки», в самом низу видим искомый MAC. Ура!

Как узнать MAC-адрес на андроиде

Мобильные гаджеты Apple

Для просмотра MAC-адреса на iPhone / iPad / iPod Touch зайдите в «Настройки», далее «Основные», затем «Об этом устройстве», в поле «Адрес Wi-Fi» указан физический адрес беспроводного модуля.

Узнать MAC-адрес Apple iPhone

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

Этот раздел расскажет вам о том, как узнать MAC-адрес удаленного компьютера. Важное условие: устройство с искомым MAC-адресом должно находиться в той же подсети, что и ваш компьютер (это может быть домашняя сеть или, например, сеть предприятия). Вам также должен быть известен его IP-адрес. Ниже приведены два способа того, как узнать MAC-адрес в сети: для OC Windows и Linux.

Windows ARP

Для того, чтобы узнать MAC-адрес компьютера по IP, можно воспользоваться ARP — встроенной утилитой Windows, представляющей собой программную реализацию сетевого протокола определения адреса (Address Resolution Protocol). Другими словами — ARP позволяет узнать физический адрес устройства по его известному адресу IP.

Для того, чтобы определить MAC-адрес удаленного компьютера (или любого другого сетевого устройства) необходимо выполнить следующую последовательность действий:

  1. Открываем «Командную строку» одним из известных вам способов.
  2. В строке пишем команду ping [адрес удаленного устройства] . Например, я хочу определить MAC-адрес маршрутизатора в своей домашней сети, тогда команда будет иметь вид: ping 192.168.1.1 .
  3. После того, как «пинг» окончен, воспользуемся командой arp -a . Результат выполнения команды покажет физический адрес удаленного роутера.

Как узнать физический адрес устройства по IP

Linux ARP

Повторим последовательность аналогичную предыдущему подразделу, но уже в терминале вашего Linux дистрибутива. В результате чего вы получите что-то вроде:

Как определить производителя по MAC-адресу

Пользователь может идентифицировать производителя своей «сетевухи» по трем старшим (первым слева) байтам. Для этого нужно вставить MAC-адрес своего устройства на специальном сервисе (например, здесь) и нажать клавишу Submit (Подтвердить).

Как узнать производителя по MAC-адресу

Вместо послесловия

Надеюсь, вы нашли данную статью интересной и, что самое главное, доступной и полезной. Мы рады, что теперь вы знаете, где и, конечно же, как узнать MAC-адрес своего или любого другого устройства в сети. Теперь вы стали еще на один шаг ближе к полному освоению компьютера!

Get network interface name and MAC address on command line

Kusalananda's user avatar

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

So, something like:

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

muru's user avatar

Using ip link

  • 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.
  • -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

C0deDaedalus's user avatar

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:

Petras L's user avatar

I made an ugly hacky one liner:

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

3 Ways to Find MAC Address In Linux

How to list MAC address on Linux is a commonly asked question during a Linux job interview. Here are some methods to get the MAC address. These commands are safe to run without changing anything.

The following commands can get you the MAC address of your network interface in Linux.

  • ifconfig -a
  • ifconfig eth0
  • ip link show
  • ip -o link show eth0
  • ip -o link show |cut -d ‘ ‘ -f 2,20
  • cat /sys/class/net/*/address

Procedures to find MAC address in Linux

  • Open the terminal application.
  • Type ifconfig -a or ip link show or cat /sys/class/net/*/address command
  • Press Enter to run the command.
  • The output will display the MAC address for all the network interfaces.

What is MAC address?

From Wikipedia, A MAC address is the unique identifier that is assigned by the manufacturer to a piece of network hardware (like a wireless card or an ethernet card). MAC stands for Media Access Control, and each identifier is intended to be unique to a particular device.

The MAC address consists of six sets of two characters, each separated by a colon. 00:1B:44:11:3A:B7 is an example of a MAC address. The MAC address is usually printed on the card itself. The MAC address can also be found in the BIOS of the computer or device.

A MAC address can be used to uniquely identify a device on a network. This allows for better security and more efficient networking. MAC addresses are usually assigned by the manufacturer of the network adapter. However, it is possible to change the MAC address of a device.

Find MAC address with ifconfig command in Linux

The best Linux command to find MAC address is using ifconfig command. All we need is to open the terminal then type ifconfig -a in the prompt. The number next to ether is the MAC address. This command will list MAC address, IP address, MTU size and other information about a network interface.

# ifconfig -a

ens1f0: flags=4163 mtu 1500
inet 10.124.202.230 netmask 255.255.255.128 broadcast 10.124.202.255
ether 70:ca:9b:ce:67:ae txqueuelen 1000 (Ethernet)
RX packets 12187970 bytes 7390885300 (6.8 GiB)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 16813496 bytes 16253942714 (15.1 GiB)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0
device memory 0xb1960000-b197ffff

By default, the ifconfig command will display information for all the network interfaces on the Linux system.

If you receive a message “ifconfig command not found” when you try to use it, you can run the following command to install it.

On Debian based distros:
# apt update
# apt install net-tools

On Red Hat based distros:
# dnf install net-tools

Check this post to get more info about how to fix ifconfig command not found

Find MAC address for a specific interface with ifconfig command in Linux

You can append the name of the interface to the end of the command (e.g. “ifconfig eth0”) to view the MAC address about a specific interface.

So if you want to display information only for specific device like eth0, you can use this command ifconfig eth0.

$ ifconfig eth0
eth0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500
inet 10.254.222.37 netmask 255.255.254.0 broadcast 10.254.223.255
ether fa:16:3e:18:3a:76 txqueuelen 1000 (Ethernet)
RX packets 94405374 bytes 5781082518 (5.3 GiB)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 23249315 bytes 1034177108 (986.2 MiB)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0

The ifconfig command can be used to configure a network interface. The basic syntax for the ifconfig command is: ifconfig interface ip address netmask BROADCAST_ADDRESS

This will set the IP address, netmask and gateway for the specified network interface.You can also use the ifconfig command to enable or disable a network interface. The basic syntax for this is: ifconfig interface up or down

The “ifconfig” command is a command-line utility that is used to display information about your network interfaces. This command is available on most Unix-like operating systems, including Linux and macOS. We can also use ifconfig command to troubleshoot network issues.

Find MAC address with ip link show command in Linux

Another way to find MAC address in Linux is using “ip link show” command. The number next to link/ether is the MAC address. This command will list the interface status, MAC address, MTU size, etc.

# ip link show

1: lo: mtu 65536 qdisc noqueue state UNKNOWN mode DEFAULT group default qlen 1000
link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
2: ens1f0: mtu 1500 qdisc mq state UP mode DEFAULT group default qlen 1000
link/ether 70:ca:9b:ce:67:ae brd ff:ff:ff:ff:ff:ff

To view information about a specific network link, you can use the “ip link show” command followed by the name of the network interface. For example, if you want to view information about the eth0 interface, you can run the following command: “ip link show eth0”.

The following command lists the interface names on the left and the associated MAC addresses on the right.

ip -o link show |cut -d ‘ ‘ -f 2,20
lo: 00:00:00:00:00:00
eth0: 02:01:e4:a2:3a:31

Find MAC address from /sys in Linux

If you want to get MAC information about the network interface, you can use this command cat /sys/class/net/*/address .

sysfs is a virtual filesystem in Linux that provides a way to access and manipulate the parameters of devices. sysfs is mounted on /sys when your system boots.

The sysfs filesystem contains a directory for each device on your system. The name of the directory is the name of the device. The contents of the directory depend on the type of device.If you want to get information about the network interfaces on your system, you can cd to /sys/class/net/.

# cat /sys/class/net/ens1f0/address
70:ca:9b:ce:67:ae

$ cat /sys/class/net/*/address
02:01:e4:a2:3a:31
00:00:00:00:00:00

Difference between MAC address and IP address

MAC addresses are physical addresses, while ip addresses are logical addresses. MAC addresses are used to identify devices on a network, while ip addresses are used to identify the location of devices on a network.

The two most common types of ip addresses are IPv4 and IPv6. IPv4 is a 32-bit address that can support up to 4.3 billion unique addresses. IPv6 is a 128-bit address that can support up to 3.4×1038 unique addresses.

MAC addresses are assigned by the manufacturer of the device. Ip addresses can be assigned by the user or by the network administrator.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *