- 15 Useful “ifconfig” Commands to Configure Network Interface in Linux
- 1. View All Network Interface Settings
- 2. Display Information of All Network Interfaces
- 3. View Network Settings of Specific Interface
- 4. How to Enable a Network Interface
- 5. How to Disable a Network Interface
- 6. How to Assign an IP Address to Network Interface
- 7. How to Assign a Netmask to Network Interface
- 8. How to Assign a Broadcast to Network Interface
- 9. How to Assign an IP, Netmask, and Broadcast to Network Interface
- 10. How to Change MTU for a Network Interface
- 11. How to Enable Promiscuous Mode
- 12. How to Disable Promiscuous Mode
- 13. How to Add New Alias to Network Interface
- 14. How to Remove Alias to Network Interface
- 15. How to Change the MAC address of Network Interface
- Other Networking Utilities
- If You Appreciate What We Do Here On TecMint, You Should Consider:
- Команда ifconfig — примеры использования
- Установка ifconfig
- Синтаксис ifconfig
- Примеры использования ifconfig
- Выводы
15 Useful “ifconfig” Commands to Configure Network Interface in Linux
ifconfig in short “interface configuration” utility for system/network administration in Unix/Linux operating systems to configure, manage and query network interface parameters via command-line interface or in a system configuration scripts.
The “ifconfig” command is used for displaying current network configuration information, setting up an ip address, netmask, or broadcast address to a network interface, creating an alias for the network interface, setting up hardware address, and enable or disable network interfaces.
15 Useful ifconfig Commands
This article covers “15 Useful “ifconfig” Commands” with their practical examples, which might be very helpful to you in managing and configuring network interfaces in Linux systems.
Update: The networking command ifconfig is deprecated and replaced by the ip command (Learn 10 Examples of IP Command) in most Linux distributions.
1. View All Network Interface Settings
The “ifconfig” command with no arguments will display all the active interfaces details. The ifconfig command is also used to check the assigned IP address of a server.
2. Display Information of All Network Interfaces
The following ifconfig command with the -a argument will display information of all active or inactive network interfaces on the server. It displays the results for eth0, lo, sit0 and tun0.
3. View Network Settings of Specific Interface
Using interface name (eth0) as an argument with the “ifconfig” command will display details of the specific network interface.
4. How to Enable a Network Interface
The “up” or “ifup” flag with interface name (eth0) activates a network interface if it is not inactive state and allowing to send and receive information. For example, “ifconfig eth0 up” or “ifup eth0” will activate the eth0 interface.
5. How to Disable a Network Interface
The “down” or “ifdown” flag with interface name (eth0) deactivates the specified network interface. For example, the “ifconfig eth0 down” or “ifdown eth0” command deactivates the eth0 interface if it is in an inactive state.
6. How to Assign an IP Address to Network Interface
To assign an IP address to a specific interface, use the following command with an interface name (eth0) and ip address that you want to set. For example, “ifconfig eth0 172.16.25.125” will set the IP address to interface eth0.
7. How to Assign a Netmask to Network Interface
Using the “ifconfig” command with the “netmask” argument and interface name as (eth0) allows you to define a netmask to a given interface. For example, “ifconfig eth0 netmask 255.255.255.224” will set the network mask to a given interface eth0.
8. How to Assign a Broadcast to Network Interface
Using the “broadcast” argument with an interface name will set the broadcast address for the given interface. For example, the “ifconfig eth0 broadcast 172.16.25.63” command sets the broadcast address to an interface eth0.
9. How to Assign an IP, Netmask, and Broadcast to Network Interface
To assign an IP address, Netmask address, and Broadcast address all at once using the “ifconfig” command with all arguments as given below.
10. How to Change MTU for a Network Interface
The “mtu” argument sets the maximum transmission unit to an interface. The MTU allows you to set the limit size of packets that are transmitted on an interface. The MTU is able to handle a maximum number of octets to an interface in one single transaction.
For example, “ifconfig eth0 mtu 1000” will set the maximum transmission unit to a given set (i.e. 1000). Not all network interfaces support MTU settings.
11. How to Enable Promiscuous Mode
What happens in normal mode, when a packet is received by a network card, it verifies that it belongs to itself. If not, it drops the packet normally, but in the promiscuous mode is used to accept all the packets that flow through the network card.
Today’s network tools use the promiscuous mode to capture and analyze the packets that flow through the network interface. To set the promiscuous mode, use the following command.
12. How to Disable Promiscuous Mode
To disable promiscuous mode, use the “-promisc” switch that drops back the network interface in normal mode.
13. How to Add New Alias to Network Interface
The ifconfig utility allows you to configure additional network interfaces using the alias feature. To add the alias network interface of eth0, use the following command. Please note that the alias network address is in the same subnet mask. For example, if your eth0 network ip address is 172.16.25.125, then the alias ip address must be 172.16.25.127.
Next, verify the newly created alias network interface address, by using the “ifconfig eth0:0” command.
14. How to Remove Alias to Network Interface
If you no longer required an alias network interface or you incorrectly configured it, you can remove it by using the following command.
15. How to Change the MAC address of Network Interface
To change the MAC (Media Access Control) address of an eth0 network interface, use the following command with the argument “hw ether“. For example, see below.
These are the most useful commands for configuring network interfaces in Linux, for more information and usage of the ifconfig command use the manpages like “man ifconfig” at the terminal. Check out some other networking utilities below.
Other Networking Utilities
- nmcli – a command-line client that is used to control NetworkManager and report network information.
- Tcmpdump – is a command-line packet capture and analyzer tool for monitoring network traffic.
- Netstat – is an open-source command-line network monitoring tool that monitors incoming and outgoing network packets traffic.
- ss (socket statistics) – a tool that prints network socket-related information on a Linux system.
- Wireshark – is an open-source network protocol analyzer that is used to troubleshoot network-related issues.
- Munin – is a web-based network and system monitoring application that is used to display results in graphs using rrdtool.
- Cacti – is a complete web-based monitoring and graphing application for network monitoring.
To get more information and options for any of the above tools, see the man pages by entering “man toolname” at the command prompt. For example, to get the information for the “netstat” tool, use the command “man netstat“.
If You Appreciate What We Do Here On TecMint, You Should Consider:
TecMint is the fastest growing and most trusted community site for any kind of Linux Articles, Guides and Books on the web. Millions of people visit TecMint! to search or browse the thousands of published articles available FREELY to all.
If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.
We are thankful for your never ending support.
Источник
Команда ifconfig — примеры использования
Команда ifconfig очень долго использовалась для настройки сети в операционных системах семейства Linux. С помощью нее вы можете включать или выключать сетевые интерфейсы, настраивать их параметры, переключать режимы и многое другое. Потом была разработана утилита ip, которая содержит больше функций, и имеет совсем другой синтаксис.
Но многие пользователи привыкли использовать ifconfig, тем более, что ее синтаксис более простой. Прочитать про утилиту ip вы можете в статье утилита ip в Linux. В этой же статье мы рассмотрим как используется ее более старый аналог — утилита ifconfig linux.
Установка ifconfig
С появлением утилиты ip, ifconfig была удалена из многих дистрибутивов. Но в большинстве она все еще поставляется по умолчанию. Установка ifconfig в Ubutnu выполняется командой:
sudo apt install net-tools
sudo pacman -S net-tools
Синтаксис ifconfig
Утилита ifconfig имеет очень простой синтаксис при вызове без параметров, она возвратит список подключенных к системе сетевых интерфейсов и их характеристики, например, ip адрес, адрес шлюза, размер пакета, частоту для беспроводных сетей и другие параметры. Если указать интерфейс и нужные команды, то можно изменять различные настройки интерфейса. Вот сам синтаксис:
$ ifconfig опции интерфейс команда параметры адрес
Интерфейс — это сетевой интерфейс, о котором вы хотите посмотреть информацию или изменить его параметры. Все это можно сделать с помощью команд. Давайте рассмотрим основные из них:
- up — включить интерфейс;
- down — выключить интерфейс;
- (-)arp — включить или выключить использование протокола ARP для интерфейса;
- (-)promisc — включить или выключить неразборчивый режим для интерфейса;
- (-)allmulti — включить или выключить режим multicast;
- metric — изменить параметр metric;
- mtu — изменить максимальный размер пакета;
- netmask — установить маску сети;
- add — добавить ip адрес для интерфейса;
- del — удалить ip адрес интерфейса;
- media — установить тип внешнего протокола;
- [-]broadcast — установить широковещательный адрес или отключить эту функцию;
- hw — установить MAC адрес для интерфейса;
- txqueuelen — размер очереди интерфейса;
Параметры и адрес необязательны и зависят от используемой команды. А опции влияют на поведение утилиты более глобально. Опций всего несколько, рассмотрим их:
- -a — применять команду ко всем интерфейсам, например, полезно, если вы хотите отключить или включить все сетевые интерфейсы;
- -s — вывести краткий список интерфейсов.
Обратите внимание, что для использования утилиты вам понадобятся права суперпользователя. А теперь давайте рассмотрим несколько примеров.
Примеры использования ifconfig
Для начала давайте просмотрим список интерфейсов, подключенных к вашей системе и активированных в данный момент. Для этого достаточно выполнить команду без параметров:
Вы можете вывести только информацию про определенный интерфейс, например, про eth0:
sudo ifconfig eth0
Чтобы посмотреть список интерфейсов с минимальной информацией о них используйте опцию -s:
sudo ifconfig -s
С помощью опции -a вы можете вывести все интерфейсы, даже те, которые сейчас отключены:
sudo ifconfig -a
Чтобы включить интерфейс используется команда ifconfig eth0 up:
sudo ifconfig eth0 up
Чтобы отключить — down:
sudo ifconfig eth0 down
Вы можете получить более подробную информацию об ошибках с помощью опции -v:
sudo ifconfig -v
Включить поддержку протокола ARP для интерфейса:
sudo ifconfig eth0 arp
Отключить поддержку ARP:
sudo ifconfig eth0 -arp
Включить неразборчивый режим, в котором интерфейс принимает все, проходящие через него пакеты:
sudo ifconfig eth0 promisc
А чтобы отключить:
sudo ifconfig eth0 -promisc
С помощью команды netmask вы можете установить маску сети для интерфейса:
sudo ifconfig eth0 netmask 255.255.255.0
Чтобы добавить ip адрес для интерфейса используйте просто укажите его после интерфейса:
sudo ifconfig eth0 192.168.1.11
Команда broadcast позволяет установить широковещательный адрес:
sudo ifconfig eth0 broadcast 192.168.1.255
С помощью команды hw вы можете установить аппаратный адрес или так называемый, MAC адрес. Здесь, кроме самого адреса нужно указать тип сети. Это ether для проводного подключения Ethernet, ax25 (AMPR AX.25), ARCnet и netrom (AMPR NET/ROM). Например:
sudo ifconfig eth0 hw ether BC:AE:C5:BE:8B:B7
С помощью mtu вы можете изменить максимальный размер пакета:
sudo ifconfig eth0 mtu 1000
Это были все основные примеры. В отличие от ip, команда ifconfig не содержит всех необходимых возможностей для полноценной настройки сети и поэтому вам еще придется использовать такие утилиты, как route или arp.
Фактически, настройка ifconfig сети будет выполняться в несколько команд. Допустим, мы будем настраивать интерфейс eth0:
sudo ifconfig eth0 up
$ sudo ifconfig eth0 add 192.168.1.10
$ sudo ifconfig eth0 netmask 255.255.255.0
$ sudo ifconfig eth0 broadcast 192.168.1.255
$ sudo route add default gw 192.168.1.1
Здесь мы используем ip адрес для компьютера 192.168.1.10, сетевую маску 255.255.255.0 и шлюз для выхода в сеть 192.168.1.1. После этих настроек осталось указать сервер DNS и интернет должен работать.
Выводы
В этой статье мы рассмотрели как работает команда ifconfig и что с ее помощью мы можем настроить. Я, как и раньше рекомендую использовать утилиту ip, так как она новее, и применяется в большинстве дистрибутивов по умолчанию. Но Linux — свободная система и вы можете использовать те инструменты, которые вам нравятся.
Источник