How to list network interfaces in Ubuntu
In Ubuntu, you can configure network interfaces at the installation time or after the complete setup of the operating system, whether it is a physical or virtual network interface. To configure network settings via the Ubuntu command line, you must first know how many network interfaces exist on the
machine. This article will show you how to list network interfaces in Ubuntu using five different methods. So let’s get started!
Method 1: How to list network interfaces in Ubuntu using ip command
Linux administrators are familiar with the “ip” command, which is a powerful tool for configuring network interfaces. The “ip” stands for Internet protocol. In Ubuntu, the “ip” command can be utilized to assign and delete addresses and routes, put up or down interfaces, control ARP cache, and more. On all modern network interfaces, “iproute” is the package that contains the “ip” utility.
Now, we will see how we can use the “ip” command for listing the network interface in Ubuntu. For this, we will utilize the “link” option with the “ip” command. This option is used to list out and modify network interfaces:
In the “ip” command, there is another option that can be used for the same purpose. Adding the “address” option in the “ip” command will also show you the list of network interfaces and their IP addresses in the Ubuntu terminal:
Method 2: How to list network interfaces in Ubuntu using nmcli command
The “nmcli” stands for Network Manager Command-Line Tool. In Ubuntu, network status is reported, and the Network Manager is controlled using nmcli. You can also utilize this tool as an alternative to nm-applet and other graphical clients. This command is also used for creating, viewing, deleting, activating, and deactivating network connections.
By using “nmcli”, if you want to list out network interfaces in Ubuntu, then write out the below-given command in your terminal:
Here “device” option will list out the network interfaces, and the “status” will display their current status on the system:
To view the profile of the network interfaces, utilize this command in your terminal:
This command will retrieve the profile information of the network interface from the “/etc/sysconfig/network-scripts” file, comprising connection name as “NAME”, Universal Unique Identifier as “UUID“, network interface type as “TYPE”, and lastly, device name as “DEVICE”:
Method 3: How to list network interfaces in Ubuntu using netstat command
Network statistics or “netstat” is another utility used in Ubuntu to display network interface statistics, routing tables and monitor incoming and outgoing network connections. This command-line tool is essential for Linux-based systems and network administrators for resolving network-related issues and determining traffic performance.
In the netstat command, the “-i” option is added to list all network interface packet transactions. Execution of the below-given will also you the active network interfaces on your Ubuntu system:
Method 4: How to list network interfaces in Ubuntu using ifconfig command
The kernel-resident network interfaces are configured with the help of “ifconfig” or interface configuration command. This utility is used for setting up the interfaces as needed at boot time. After that, it is typically used only when system tuning or debugging is required. You can also use “ipconfig” command for the assignment of an IP address and netmask to an interface and to enable or disable it.
The below-given command will list out all the network interfaces of your Ubuntu system even if they are not active:
You can also utilize the below-given command for the same purpose:
Method 5: How to list network interfaces in Ubuntu using the “/sys/class/net/” file
The “/sys/class/net/” file contains the names of network interfaces or the network cards on your system. Utilize the “ls” command to list out the network interfaces present in this file:
Conclusion
When you operate as a Linux administrator, you are responsible for managing the system’s network configuration. Both physical and virtual network interfaces can be configured at installation or after setting up the whole Ubuntu system. To make any required changes in the network interface, you must know the information related to network interfaces. This article demonstrated how to list network interfaces in Ubuntu using five different methods. All of the discussed utilities are simple and easy to implement. Try any of them for getting a list of your network interfaces.
About the author
Sharqa Hameed
I am a Linux enthusiast, I love to read Every Linux blog on the internet. I hold masters degree in computer science and am passionate about learning and teaching.
4 Ways to Find network interfaces in Linux
Linux provides a number of commands to manage network interfaces. In this post, we will discuss 4 different commands: ifconfig, ip addr, ip link show, dmesg.
The ifconfig command displays information about all active network interfaces on your system. However, this command has been deprecated in favor of ip command.
The ip command is a powerful replacement for the older ifconfig command that can be used to manage network interfaces and routing tables.
The dmesg command can be used to display the kernel ring buffer, which contains messages from the Linux kernel. These messages can include information about the system hardware, software, and network interfaces.
These commands are safe to run without changing anything.
Here are the commands and options we can use to get the network interfaces.
- ifconfig -a
- ifconfig eth0
- ip addr
- ip link show
- ip link show dev eth0
- dmesg | grep -i eth
Procedure to get network interfaces in Linux
- Open the terminal application.
- Type ifconfig -a or ip addr or ip link show
- Press Enter to run the command.
- The output will list all the network interfaces
Find network interfaces with ifconfig command in Linux
The best Linux command to find network interfaces is to use ifconfig command. Open the terminal and type “ifconfig -a”. This will return a list of all available network interfaces on Linux system.
If you do not specify an interface name, the ifconfig command will display information for all of the network interfaces on the system.
$ ifconfig -a
eth0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 9001
inet 10.1.0.203 netmask 255.255.255.0 broadcast 10.1.0.255
ether 02:1b:4c:94:27:1b txqueuelen 1000 (Ethernet)
RX packets 1716963 bytes 472994059 (451.0 MiB)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 7964635 bytes 11377273850 (10.5 GiB)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0
You can append the name of the interface to the end of the command (e.g. “ifconfig eth0”) to view information about a specific interface.
So if I want to display information only for specific device like eth0, I will 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
This command is available on most Unix-like operating systems, including Linux and macOS.
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
To get more details about this command, I highly recommend the following article.
Find network interfaces with ip add command in Linux
Another way to find your network interface in Linux is to use the ip command. The ip command displays a variety of information about your system’s networking configuration.
To view information about all available interfaces, type “ip addr” into a terminal. This will return a list of interfaces along with their assigned IP addresses.
The ip command is one of my favorite commands to use on the terminal. This command is an incredibly useful tool for network configuration and troubleshooting.
This command also allows you to configure network interfaces, add routes, and manipulate network devices.
Whether I am setting up a new network or resolving a connectivity issue, the ip command is an essential part of my toolkit.
$ ip addr
1: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 9001 qdisc mq state UP group default qlen 1000
link/ether 02:1b:4c:94:27:1b brd ff:ff:ff:ff:ff:ff
inet 10.1.0.203/24 brd 10.1.0.255 scope global dynamic noprefixroute eth0
valid_lft 3029sec preferred_lft 3029sec
If you want to display information only for specific device like em1, you can use this command ip addr show dev em1.
To learn more about ip command, I highly recommend the following guide.
List network interfaces with ip link show command in Linux
The ip link show command can also be used to find your network interface in Linux.
To view information about a specific interface, simply append the interface number to the end of the command (e.g. “ip link show eth0”).
$ ip link show
1: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 9001 qdisc mq state UP mode DEFAULT group default qlen 1000
link/ether 02:1b:4c:94:27:1b brd ff:ff:ff:ff:ff:ff
check network interfaces with dmesg command in Linux
If you are unsure of the name of your network interface, you can use the dmesg command to find it. The dmesg command prints messages from the kernel ring buffer. This information can be useful for finding hardware devices on your system.
To use this command, type “dmesg | grep -i eth” into a terminal. This will return a list of lines that contain the word “eth”, which is typically used to identify network interfaces.
$ sudo dmesg |grep -i eth
[ 20.680677] IPv6: ADDRCONF(NETDEV_UP): eth0: link is not ready
what is network interface in Linux
The network interface in Linux is a term used to describe the device that your computer uses to connect to a network. This could be a wired or wireless connection, depending on your setup.
Network interfaces can take various forms, such as wired Ethernet adapters, wireless adapters, or virtual interfaces.
This interface is responsible for transmitting and receiving data over the network, allowing the computer to access the internet or communicate with other devices on the network.
The network interface is usually represented by the eth0 or wlan0 device in Linux, but it may vary depending on your system.
How to find the MAC address of network interface in Linux?
Each NIC has a unique address (the hardware address, known as Media Access Control [MAC] address), which identifies that NIC.
This address is six pairs of hexadecimal bits separated by colons (:). A MAC address looks similar to this: 00:60:08:8F:5A:D9.
The MAC address of a device in Linux can be found using the ifconfig command. This will print the MAC address for your network interfaces. You can also use the ip link show command to find the MAC address.
How to find the IP address of network interface in Linux?
To find your IP address in Linux, use the ip addr command. This will print the IP address and other information about your network interfaces.
If you want to find out your public IP address, you can use the curl command. This will send a request to a web server and return your public IP address. curl ifconfig.me
How to find the gateway of network interface in Linux?
To find the gateway in Linux, you can use the route command. This will print the IP address of the gateway for your default route. You can also use the ip addr command to find the gateway.
I hope this blog post has been helpful in finding your network interface in Linux. If you have any questions, feel free to leave a comment below! Thanks for reading!
Как найти доступные сетевые интерфейсы в системах Linux
Мануал
Мы можем настроить сетевые интерфейсы в Linux во время установки.
Но некоторые из вас могут предпочесть сделать это после установки или изменить существующие настройки.
Как вы уже знаете, для настройки сетевых параметров из командной строки необходимо сначала узнать, сколько интерфейсов доступно в системе.
В этом подробном руководстве рассматриваются все возможные способы перечисления и поиска доступных сетевых интерфейсов в операционных системах Linux и Unix.
1. Отображение сетевых интерфейсов с помощью команды ifconfig
Наиболее часто используемый метод поиска информации о сетевом интерфейсе – команда ifconfig.
Я полагаю, что некоторые пользователи Linux все еще используют ее.
Как видно из приведенного выше вывода, у меня есть два сетевых интерфейса, а именно enp5s0 (встроенный адаптер проводной сети Ethernet) и wlp9s0 (адаптер беспроводной сети) на моей Linux-машине.
Также lo – это интерфейс loopback, который используется для локального доступа ко всем сетевым сервисам.
Он имеет IP-адрес 127.0.0.1.
Мы также можем использовать ту же команду ‘ifconfig’ во многих вариантах UNIX , например, во FreeBSD , для получения списка доступных сетевых карт.
2. Вывод списка сетевых интерфейсов с помощью команды ip
Команда ‘ifconfig’ устарела в последних версиях Linux.
Поэтому вы можете использовать команду ‘ip’ для отображения сетевых интерфейсов, как показано ниже.
Пример вывода:
Вы также можете использовать следующие команды:
Заметили ли вы, что эта команда также показывает состояние подключения сетевых интерфейсов?
Если вы внимательно посмотрите на приведенный выше вывод, вы заметите, что моя карта Ethernet не подключена сетевым кабелем (см. слово “DOWN” в приведенном выше выводе).
А беспроводная сетевая карта подключена (см. слово “UP”). Для получения более подробной информации ознакомьтесь с нашим предыдущим руководством по поиску подключенного состояния сетевых интерфейсов в Linux.
Этих двух команд ( ifconfig и ip ) достаточно, чтобы найти доступные сетевые карты в ваших системах Linux.
Однако в Linux существует несколько других способов составления списка сетевых интерфейсов.
3. Выводим список сетевых интерфейсов с помощью каталога /sys/class/net/
Ядро Linux сохраняет информацию о сетевых интерфейсах в каталоге /sys/class/net.
Вы можете проверить список доступных интерфейсов, заглянув в этот каталог.
Вывод:
4. Смотрим список сетевых интерфейсов с помощью файла /proc/net/dev
В операционных системах Linux файл /proc/net/dev содержит статистику о сетевых интерфейсах.
Чтобы просмотреть доступные сетевые карты, просто просмотрите его содержимое с помощью команды:
Вывод:
5. Строим список сетевых интерфейсов с помощью команды netstat
Команда netstat отображает различные детали, такие как сетевые соединения, таблицы маршрутизации, статистику интерфейсов, маскарадные соединения и многоадресные членства.
Вывод:
Пожалуйста, имейте в виду, что netstat устарел.
Заменой для “netstat -i” является “ip -s link”.
Также обратите внимание, что этот метод выведет список только активных интерфейсов, а не всех доступных интерфейсов.
6. Находим список сетевых интерфейсов с помощью команды nmcli
nmcli – это инструмент командной строки для управления NetworkManager и составления отчетов о состоянии сети.
Он используется для создания, отображения, редактирования, удаления, активации и деактивации сетевых соединений и отображения состояния сети.
Если у вас установлена система Linux с Network Manager, вы можете перечислить доступные сетевые интерфейсы с помощью инструмента nmcli, используя следующие команды:
Вывод:
Вы также можете использовать эту команду для отображения сетевых интерфейсов в вашей системе Linux:
Большинство вышеупомянутых утилит предустановлены в большинстве систем Linux и Unix.
Существует еще несколько внешних утилит для отображения списка сетевых карт.
7. Как показать список сетевых интерфейсов с помощью hwinfo
Hwinfo – это утилита командной строки для просмотра информации об аппаратном обеспечении в системе Linux.
Она проверяет наличие аппаратного обеспечения в системе Linux и отображает подробную информацию о каждом аппаратном устройстве.
Hwinfo доступна в официальных репозиториях многих дистрибутивов Linux.
Чтобы установить hwinfo в системах на базе RPM, выполните команду:
На системах на базе Deb вы можете установить hwinfo с помощью следующей команды:
После установки выполните следующую команду, чтобы перечислить имена сетевых интерфейсов с помощью утилиты hwinfo:
Вывод:
8. Как показать сетевые интерфейсы с помощью lshw
Lshw (Hardware Lister) – это утилита CLI, которая предоставляет подробную информацию об аппаратной конфигурации системы Linux.
Чтобы показать список сетевых карт в Linux с помощью утилиты lshw, выполните следующие действия:
Вывод:
9. Просмотр сетевых интерфейсов с помощью inxi
Inxi – это еще один инструмент для получения системной информации из командной строки, такой же, как hwinfo и lshw.
Он показывает аппаратное обеспечение системы, процессор, драйверы, Xorg, рабочий стол, ядро, версию(и) GCC, процессы, использование оперативной памяти и множество другой полезной информации.
Чтобы показать информацию о сетевых картах, включая производителя, драйвер карты и количество доступных сетевых интерфейсов в системе Linux, запустите inix с опцией -N:
10. Отображение сетевых интерфейсов с помощью команды lspci
Команда lspci выводит список всех PCI-устройств в системе Linux.
Чтобы просмотреть список доступных сетевых интерфейсов в системе Linux, используйте lspci с командой egrep, как показано ниже:
Вывод:
Как вывести только имена доступных сетевых интерфейсов
До сих пор мы рассматривали различные методы поиска доступных сетевых интерфейсов в Linux.
Во всех вышеупомянутых методах мы отображали доступные сетевые интерфейсы вместе с некоторыми дополнительными деталями, такими как данные RX/TX, Mac-адрес, состояние подключения, режим, тип сети и некоторые другие.
Если вы хотите убрать ненужные детали и перечислить только название сетевых интерфейсов, вы можете использовать одну из следующих команд.
Вывод:
Чтобы исключить устройство loopback (lo) из вывода, выполните эту команду:
Как было сказано ранее, команда ifconfig устарела.
Если команда ifconfig недоступна, используйте команду ip для отображения только имен сетевых интерфейсов с флагом -o, как показано ниже:
Вы также можете использовать следующую команду:
Заключение
В этом руководстве мы рассмотрели десять различных методов поиска и вывода списка доступных сетевых интерфейсов в Linux и Unix
. Мы также рассмотрели несколько способов отображения только имени сетевых интерфейсов в системах Linux.
How can I find available network interfaces?
This is in regard to linux, but if anyone knows of a general *nix method that would be good.
I booted a system yesterday with an ethernet cable plugged in. «NetworkManager» is not installed, so once it started I went to look for the name of the ethernet interface with ifconfig to start a DHCP client manually, but it did not show anything other than lo .
The NIC was listed via lspci , and the appropriate kernel driver was loaded. The system normally uses wifi, and I could remember the interface name for that was wlan0 . When I tried ifconfig wlan0 up , wlan0 appeared. But the only ethernet interface names I could remember were eth[N] and em[N] — neither of which worked.
This document refers to «predictable interface names» but does not do a good job of explaining what they might be in simple terms. It does refer to a piece of source code which implies the name in this case might be deduced from the the PCI bus and slot numbers, which seems like an unnecessarily complicated hassle.
Other searching around led me to believe that this might be determined by systemd in conjunction with udev , but there are almost 100 files in /usr/lib/udev/rules.d and spending an hour trying to determine where (and if) there’s a systemd config file for this also seems ridiculous.
It would also be nice to know for certain that they are available, not just how they might be named if they are, so I can rule out hardware problems, etc. Isn’t there a simple way to find the names of available network interfaces on linux?