Linux get interface name

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 

Источник

Читайте также:  Стандартный словарь kali linux

Список сетевых интерфейсов Linux

В операционной системе Linux не только жесткие и SSD диски представлены файлами в специальной файловой системе, но и сетевые интерфейсы. Существует несколько способов посмотреть список сетевых интерфейсов Linux, но самый простой из них — это просто посмотреть содержимое папки в файловой системе.

В этой небольшой статье мы рассмотрим все основные способы выполнить эту задачу в терминале или графическом интерфейсе.

Список сетевых интерфейсов Linux

Сетевые интерфейсы проводного интернета Ethernet обычно имеют имя, начинающиеся с символов enp, например, enp3s0. Такое именование используется только если ваш дистрибутив использует systemd, иначе будет применена старая система именования, при которой имена начинаются с символов eth, например eth0. Беспроводные сетевые интерфейсы, обычно называются wlp или wlx при использовании systemd, например, wlp3s0. Без использования systemd имя беспроводного интерфейса будет начинаться с wlan, например wlan0. Все остальные интерфейсы обычно виртуальные. Один из самых основных виртуальных интерфейсов — lo. Это локальный интерфейс, который позволяет программам обращаться к этому компьютеру. А теперь рассмотрим несколько способов посмотреть их список.

1. Файловая система

Все файлы устройств сетевых интерфейсов находятся в папке /sys/class/net. Поэтому вы можете посмотреть её содержимое:

2. Утилита ifconfig

Утилита ifconfig выводит не только список сетевых интерфейсов, но и информацию о них, такую как состояние, IP адрес, MAC адрес и другие параметры. Для отображения всех интерфейсов достаточно выполнить программу без параметров:

3. Утилита ip

Программа ifconfig устарела и ей на смену пришла утилита ip. Она объединяет в себе функции нескольких программ, например ifconfig, route, brctl и других. Посмотреть список устройств с помощью ip можно выполнив команду:

Здесь информации намного меньше, показывается только состояние устройства, MTU и ещё несколько параметров. Можно вывести информацию в более компактном виде, использовав опцию -br:

В таком случае все данные отображаются в одну строчку, выводится состояние, MAC адрес и ещё несколько опций.

4. Утилита nmcli

Посмотреть всю нужную информацию можно и с помощью консольной утилиты управлением брандмауэром — nmcli:

Здесь выводится подключение NetworkManager, связанное с конкретным устройством, а также его состояние.

5. Утилита netstat

Программа netstat тоже умеет показывать сетевые интерфейсы и статистику по переданным данным если ей передать опцию -i:

6. Файл /proc/net/dev

В файле /proc/net/dev тоже содержится список всех сетевых интерфейсов, а также статистика их использования:

Выводы

Теперь вы знаете как посмотреть сетевые интерфейсы в Linux, как видите, это очень просто сделать. Если у вас остались вопросы, спрашивайте в комментариях!

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

Источник

How to find network interface name

which is fine, but some machines for some reason use eth1 instead of eth0. I would like to be able to discover the LAN iface name, so I can substitute it in here instead of eth0. Of course, if you can come up with a different oneliner that does the same thing, all good.

Читайте также:  Linux команда терминала создать файл

display the most active ethernet interface: arp -n -H ether | perl -ne ‘print $1 if /(\S+\n)$/’ | sort | uniq -c | grep -v Iface | sort -n | tail -1 | perl -pe ‘s/.* //’

7 Answers 7

The main NIC will usually have a default route. So:

ip -o -4 route show to default 
ip -o -4 route show to default | awk '' 
ip -o -4 route show to default | awk '' 

Unlike ifconfig, ip has a consistent & parsable output. It only works on Linux; it won’t work on other Unixen.

Not sure if this helps, but it seems that ip route get will show which interface it uses to connect to a remote host.

ubuntu@ip-10-40-24-21:/nail/srv/elasticsearch$ ip route get 8.8.8.8 8.8.8.8 via dev eth0 src

of course you could automate that in shell script with something like,

It seems like on my Ubuntu 15.10 machine this shows the IP address instead of the interface name. @user150471 ‘s answer below works: stackoverflow.com/a/30201105/1069083

Very good! I like this answer because of its versatility in different situations. All one really needs to know is the Ip address of a destination; ip route takes it from there.

Most recenttly systemd/udev has automatically started to assign interface names for all local Ethernet, WLAN and WWAN interfaces to something that we’re all accustomed to . This is a departure from the traditional interface naming scheme («eth0», «eth1», «wlan0», . ) .. now we have to check first what the local interface name is before we can use it while previously we it was a pretty accurate guess that «eth0» was the right name. What you’re asking for is the network NAME .. Here’s a small script to solve the problem

  1. Use «ip route get 8.8.8.8 » to figure out which ACTIVE interface has the route to internet ( or currently being used ) Output should look like : 8.8.4.4 via 10.10.1.1 dev enp0s3 src 10.10.1.118 cache
  2. Use awk to print the 5th text block for Interface NAME ]# ip route get 8.8.8.8 | awk — » Output : enp0s3
  3. Use awk to print the 7th text block for Interface Address ]# ip route get 8.8.8.8 | awk — » Output : 10.10.1.118

Great answer. I find that the ip command outputs two lines («cache and ipid 0x2e6e» on 2nd line). So ip route get 8.8.8.8 | head -n1 | awk — ‘‘ works for me!

Источник

How can i get the name of the interface, its type and ip?

what about interfaces without type (eg: real interfaces)? what about multiple addresses? what about IPv6?

Читайте также:  Remote desktop servers linux

real interfaces it is ethernet type?no? only the ipv4 family should be output, if there is more than one address then display all

actually I oversimplified there are type, kind and slave kind. a vlan interface is type ether and kind vlan. nmcli chooses to display only the kind when there’s a kind and display the type when there’s no kind

I am almost our what we need) » ip -o a show | cut -d ‘ ‘ -f 2,7 » but the question remains with the type

2 Answers 2

ip -details gives addtional information like the interface kind (see later).

For real parsability, choose the JSON output and a JSON parser: jq .

Here’s what is a one-liner but that I choose to display split over multiple lines for readability. Requires the jq utility that should be packaged in most distributions, to parse ip -json ‘s output. jq‘s language isn’t difficult to learn just by reading the link I provided.

ip -details -json address show | jq -j ' .[] | .ifname," ", .link_type,"/", .linkinfo.info_kind // "", if .linkinfo.info_slave_kind then "/slave-",.linkinfo.info_slave_kind else empty end, " ", ( .addr_info[] | ( .local," " ) ), "\n" ' 

About interface type: actually there are two direct properties: type and kind, and a 3rd property: slave_kind easily distinguishable from the second property only in JSON output.

  • type Usually loopback (only for the loopback interface), ether (most interfaces are Ethernet or Ethernet-like), or none for Layer 3 interfaces (eg: a wireguard interface).
  • kind That’s what is usually thought as type. the loopback interface and real hardware interfaces (at least common Ethernet or Wireless) don’t have a kind property.
  • slave kind When an interface is enslaved, eg to a bridge or to a bond device, then this information is available in the output of the command.

you get the combined type + kind + slave kind (if you don’t want all, just remove the relevant line(s)).

So for some subtleties, a combined ether/tun would be a tuntap device in tap mode, while a none/tun would be a tuntap device in tun mode (this information is also available directly in some sub field, but with the combined type+kind, no need).

To display only interfaces with at least one IPv4 address, the easiest is to add the -4 option along the other options to the ip address command above. As this will also remove the link-layer address, interfaces without IPv4 address won’t be matched by the filter and won’t be displayed at all.

To remove the IPv6 output but else display all interfaces, don’t add -4 but instead replace:

( .addr_info[] | ( if .family == "inet" then .local," " else empty end ) ), 

Источник

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