Network interface type linux

Naming convention standard for Ethernet and Wi-Fi interfaces on Linux machines

What is the naming convention standard for Ethernet and Wi-Fi interfaces on a Linux machine? We are developing a tool that should show only the Ethernet and Wi-Fi interfaces of the Linux machine and its current status. For example, below is the list of network interfaces (both physical and virtual) on my Linux (Ubuntu) machine: docker0 , enp0s25 , lo , wlp3s0 When I run the tool, below is the result I get: enp0s25 , wlp3s0 We have written the code with the logic that all the Ethernet interfaces always start with the letter e and Wi-Fi interfaces always start with the letter w . Is the logic right? If not, how can we address this?

Is there a reason why you wouldn’t look at something like lshw? Specifically inspect the contents of lshw -class network maybe? Look for everything that is capabilities: ethernet physical ? Possibly look for some of the other capabilities also?

To deal with the frame challenge raised by @dirkt, a better question would be simply: «how do I get the type of a network interface on Linux (or macOS, or other. )?»

7 Answers 7

Network interfaces can be named anything, so no matter what you do, you’ll run into situations where (1) there is a «physical» network interface with a name that didn’t match your pattern, or (2) there is a «physical» network interface that will match your pattern.

On top of that, if I was a user of your tool, the moment your tool wouldn’t allow me to do something I want, because I have a network interface which is «virtual», though for practical purposes it should be considered «physical» in my setup, I’d start cursing loudly and forcefully at your app, and won’t ever use it again.

Physical and virtual network interfaces all share a common API are one thing which makes Linux really flexible. Please don’t try to babysit your user, and take that away from him or her. Your users will thank you.

You haven’t actually answered the question; you’ve spent 3 paragraphs challenging the background context of the question. While I’m aware that frame challenge answers are a thing, this doesn’t feel like one of those cases . especially since user4556274 gave a succinct answer to the question as asked.

@MikeOunsworth: The problem is that the answer of user4556274 doesn’t work in the general case, it only works if the interface names are indeed predicatable interface names. Which a simple ip link set . name . can change. And yes, I could have listed the predictable interface names myself. The answer to the original question is «please don’t do it that way». Because no matter how you go about it, it won’t work.

@fpmurphy1 No, I think he means predictable interface names. Doesn’t matter if it’s systemd, traditional (ethN), your company’s specific conventions or any other standards which make the names predictable

Читайте также:  Cad систем для linux

@MikeOunsworth: The answer is in the very first sub-clause of the very first sentence of the very first paragraph: «Network interfaces can be named anything […]» Therefore, what the OP is asking about is impossible and cannot possibly be done. You cannot detect the type of a network interface based on a naming convention standard, because there is no naming convention standard and anybody can name their interfaces anything they want. For example, on my old Linux router, I head colored stickers on the back, and the physical Ethernet interfaces were named red , blue , and green .

@JörgWMittag, of course you can detect them based on a standard, if you know the standard is used (and you’re expecting one that exports that information in the name in the first place). We know systemd has a standard for network interface naming, so it’s no use saying one doesn’t exist.

For systemd’s predictable interface names, the prefixes can be seen in udev-builtin-net_id.c . They are two-character prefixes based on the type of interface:

Meaning for both the traditional ethX style of naming and the newer systemd naming, an initial letter e should be an Ethernet interface for any automatically generated interface names. All Wi-Fi interfaces should begin with a w in both schemes, although not all interfaces beginning with w will be Wi-Fi.

If this tool has to work in an arbitrary environment (rather than just on internal environments which you control), note that users may rename interfaces on Linux systems with arbitrary names, such as wan0 , lan0 , lan1 , dmz0 which will break any assumptions about initial letters.

Note that this solution won’t work on systems using biosdevname for interface naming, where an Ethernet interface can be named like p3p7 . This method is a predecessor of the new systemd predictable names and although it’s now deprecated on common distros, there will still be many systems that picked it up when it was the default a few years ago.

@user1908704: Usually this means that udev was told to give the same name to multiple interfaces. (Perhaps you have an old auto-generated «persistent names» file in /etc/udev/rules.d?) That said, the rename process was fixed in v187 to be fully atomic (either succeed or rollback) and the rename%u format hasn’t existed in the source code since 2012. I would like to sigh at your software being six years out-of-date.

@grawity This is Ubuntu 18.04. It turns out particular motherboards have two NICs with the same ACPI entry, resulting in them both being eno1. Since that can’t happen, one of them gets called ‘rename3’. I haven’t fully worked out the logic of who wins the race, but any changes can perturb the contest and cause the other to be rename3.

The naming convention is that LAN interfaces are named eth0 , eth1 , . and that WLAN interfaces are named wlan0 , wlan1 , .

What you see are the so called «predictable names» that systemd introduced. In practice, they are anything but predictable, and they can even change when the hardware is changed, which is exactly the problem they are supposed to avoid.

Читайте также:  Linux headers amd64 ubuntu

For a guess the start letter may be good enough. Some interfaces, in particular WLAN, have hints in /sys/class/net/*/uevent :

Unfortunately, there is no such DEVTYPE for LAN interfaces.

Device name changes when the hardware changes is not the problem predictable interface names is trying to avoid. Predictable interface names avoids name changes when the hardware is unchanged. This is a problem when the hardware devices are detected in a random order.

@JohanMyréen That is wrong: «. that they (interface name) stay fixed even if hardware is added or removed» freedesktop.org/wiki/Software/systemd/…

The motivation for introducing the predictable interface names was that probing is not deterministic and «the assignment of the names «eth0», «eth1» and so on not fixed anymore and it might very well happen that «eth0» on one boot ends up being «eth1″ on the next.» It is a bonus if the predictable names can survive hardware changes, but this was not the primary reason for them.

Win some lose some — in some scenarios, it is very desirable if changed hardware reliably clicks into the same «naming slot» 🙂

@JohanMyréen The old scheme of assigning interface names based on MAC or some other properties worked more reliable when adding interfaces, without the hassle of the new names.

One caveat with my answer (applies to most of the others, too): I don’t know the purpose of your application. If it is a throwaway application to troubleshoot one particular problem, or to understand networking better, never to be used again, then relying on the first letter of the interface may be a great quick-and-dirty option. If you are planning to write the next competitor to Wireshark or tcpdump, you need to be sure you get it right for all kinds of edge cases.

And if the application you are writing falls somewhere between those extremes, only you (and your customers) can know how carefully you need to implement your logic.

Others have already pointed out that the names are never reliable, for any number of reasons. The ultimate problem is a very common one in software: hard-coding assumptions instead of relying on known/documented facts.

The second issue that hasn’t been mentioned is also based on an assumption about your requirements: that the list of interfaces you want to list is always exactly «hardware ethernet interfaces» and «wifi interfaces».

The third issue is yet another assumption: that all interface will fall into the categories you can think of right now. How about Infiniband, as mentioned by @user4556274? How about tunnel interfaces for a VPN? How about bridged interfaces? How about bridged interfaces that combine physical and logical interfaces?

But there may be options to accomplish what you are looking for. First, define exactly what characterizes an interface you want to list, vs one that you don’t.

In most cases, one characteristic you can rely on is the routing table (however, this will only work as long as the interface is up, so it may not be what you are actually looking for).

Читайте также:  Поменять атрибуты файла linux

Any interface that has a default route (i.e., a route to 0.0.0.0) is likely to be one you are looking for.

Note that even this is still based on an assumption, just a more reliable one: it is conceivable that a system is configured to route all outbound traffic through a virtual machine or a docker container (for instance, if there is a container running a firewall). And the reverse is also true: a sysadmin could potentially lock down outside traffic by deleting the default route.

Another option is to go by the actual hardware and see which driver it uses. You can then exclude certain well-known drivers

Источник

Список сетевых интерфейсов 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.

Источник

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