Editor’s note: This article was written while James Brigman was a member of the Red Hat Accelerator program.
Almost any useful work that one would want to do with a Linux system requires a network interface. Want to browse the web, watch YouTube, stream video, audio or files? It’s all done over the network interface. RPM-based Linux distributions using Gnome have several fundamental ways to configure the network interface. I’m describing three ways in this article. All of the configuration methods require the entry of sets of numbers that allow the network interface to operate.
You will need three fundamental pieces of numerical information in order to minimally configure a network interface to work over IPv4 and more if you want to define things like IPv6, hostnames, or DNS servers. This article covers the bare minimum for IPv4. Those three fundamental numerical pieces are:
IP Address: The unique number defining the access point to your network interface. It has the form: xxx.xxx.xxx.xxx, where “xxx” are three, or fewer, numbers between 0 and 255. It’s possible for this number to be purely made up, but normally it takes a form that works with the other three numbers. If you are using a home router with DHCP, which is the typical default configuration, the router will “assign” the IP address to your network interface. You won’t have to enter the number at all.
Gateway: The unique number assigned to the network interface at the «other end of the wire» that your computer must communicate through. Again, it has the general xxx.xxx.xxx.xxx format and takes a form that also works with the other two numbers. If you are using a home router, your home router generates this number because it is the gateway through which you communicate with the wider world.
Netmask: The non-unique number that defines the network itself. This number can be automatically generated but is sometimes requested by the method you use to configure the interface. It, too, has the format xxx.xxx.xxx.xxx.
Note that I’m not going into the how of these numbers; I’m just telling you they are needed to configure the network interface. I’ll skip that so you can get on into the point of the article: Three ways to configure network interfaces. In each case, the numbers I use will be real numbers applicable to the system I used to write this article. I used CentOS 8 to generate the images, but everything you see here is the same in Fedora and Red Hat Enterprise Linux.
At installation time
The Anaconda installer prompts for network configuration and you can’t complete the installation without providing these numbers to the installer. Here’s the initial screen, using “Network & Host Name” in the rightmost column, third selection down:
Источник
How to configure network in Red Hat Linux
Configuring network in Red Hat Linux can be hectic and confusing if you don’t know the parameter details which are used. Also from Red Hat 6 the configuration parameter has been changed for network-config. Let me show you out the steps to do the same along with some possible explanation.
The configuration files used for complete network configuration in Red Hat 6 are /etc/sysconfig/network-scripts/ifcfg-eth0 (can vary as per the NIC present) /etc/nsswitch.conf /etc/resolv.conf
Command Line configuration
Here below is a sample file configuration for ifcfg-eth0
yes — This device should be activated at boot-time.
no — This device should not be activated at boot-time.
where answer is one of the following:
yes — NetworkManager is permitted to configure this device.This is the default behavior and can be omitted.
no — NetworkManager is not permitted to configure this device.
none — No boot-time protocol should be used.
bootp — The BOOTP protocol should be used.
dhcp — The DHCP protocol should be used.
where answer is one of the following:
yes — Non-root users are allowed to control this device.
no — Non-root users are not allowed to control this device.
yes — Modify /etc/resolv.conf if the DNS directive is set. If using DHCP, then yes is the default.
no — Do not modify /etc/resolv.conf .
In case you have used directive no for the parameter PEERDNS then you will have to manually update your resolv.conf file.
# vi /etc/resolv.conf nameserver 8.8.8.8
Step 3: Configure /etc/nsswitch.conf #hosts: db files nisplus nis dns hosts: files dns
GUI configuration
GUI configuration can be done either on command line as well as on the GNOME or KDE desktop.
Make sure the following package is installed # rpm -qa | grep system-config-network system-config-network-tui-1.6.0.el6.2-1.el6.noarch # system-config-network Follow the screenshots (Click on the image for clear view) Hit Enter on “Device Configuration“
Select the device and hit Enter
Fill up the required details as shown below and click on OK
Once you click on OK you will reach on the first page of action. Select DNS Configuration and hit enter
Fill up the required details as shown below and hit Enter
Once you have filled up all detail move the cursor to Save and Quit and Hit Enter
Источник
Red hat linux network setup
Рассмотрим конфигурирование сети в операционных системах по управлением Red Hat Enterprise Linux (RHEL) / CentOS / Fedora.
Red Hat Enterprise Linux (RHEL) — Операционная система на снове Linux выпускаемая компанией Red Hat для корпоративного использования и распространяется по годовой платной подписке. Состоит из хорошо провереных и отлаженных компонентов.
Fedora — Операционная система выпускаемая также компанией Red Hat, но в отличие от RHEL проект Fedora распространяется свободно, на Fedore тестируются новых разработки компании Red Hat, которые в дальнейшем уже испольуются для корпоративно дистрибутива RHEL.
CentOS — Операционная система основанная на исходном коде RHEL и по сути является ее клоном. Проект был создан и поддерживается интернациональной командой энтузиастов.
Основные конфигурационные файлы.
Сетевые настройка осуществляется методом правки конфигурационных файлов, т.к. Fedora и CentOS основаны на RHEL, то и сами файлы настроек и их расположение однинаковое, поэтому дальнейшие примеры настроек будут подходить ко всем трем дистрибутивам.
Файл настройки общей интформации /etc/sysconfig/network
В этом файле задается сетевое имя компьютера (HOSTNAME), дефолтный маршрут (GATEWAY), DNS-домен (DOMAINNAME).
Пример конфигурации в файле network для Red Hat / CentOS / Fedora.
В этих файлах настраиваются основные данные для сетевых интерфейсов такие как ip адрес (IPADDR), сетевая маска (NETMASK), адрес сети (NETWORK), braodcast адрес (BROADCAST). Под звездочкой понимается имя сетевого интерфейса, например eth0, eth1, eth2, lo и т.п., зависит от количества установленных сетевых карт в системе.
Приведу пример файла cо статической настройкой сетевых параметров интерфейса eth0 для Red Hat / CentOS / Fedora.
Пример файла с настройкой интерфейса eth1 на получаение сетевых адресов по протоколу DHCP для Red Hat / CentOS / Fedora.
Также во всех система присуствует файл с настройками loopback интерфеса (lo).
Все записи о статических маршрутах содержащемся в этом файле будут автоматически добавлены при загрузке системы в таблицу маршрутизации. В формае записи маршрута сначала идет интерфейс, можно указать any, что будет означать любой интерфейс, потом идет тип маршрута (host — адрес хоста или net — адрес сети) , сеть, маска данной сети, и шлюз.
Скрипт для настройки статических маршрутов для конкретного интерфейса /etc/sysconfig/network-scripts/route-eth0
Если данного файла вы ненайдете в системе неотчаивайтеь просто создайте его и пропишити нужный вам маршрут.
Файл /etc/hosts
Впоследнее время неактуален раньше использовался для соответствия списока ip-адресов и символьных имен.
Файл настроек DNS серверов /etc/resolv.conf
В этом файле перечисляется список ip адресов DNS серверов.
Управление сетевыми интерфейсами.
Для просмотра состояния и конфигурации интерфейса существуют специальные команды.
Посмотреть таблицу маршрутизации модно используя команду:
В Red Hat Enterprise Linux (RHEL) / CentOS / Fedora существуют специальные сценарии для управления сетевыми интерфейсами.
Сценарии ifup и ifdown позволяют включить или отключить сетевой интерфейс. В качестве аргумента эти сценарии принемают имя интерфейса.
Сценарий service network или /etc/init.d/network позволяют включить (start), отключить (stop) или перезапустить (restart) все интерфейсы разом.
И на последок, функция маршрутизации между интерфейсами по умолчанию отключена, однако ее можно включить для этого надо добавить в файл /ete/sysctl.conf запись net.ipv4.ip_forward=1 и перезапустить систему.
На этом рассмотрение настройки сети в операционных системах Red Hat Enterprise Linux (RHEL) / CentOS / Fedora завершено.
Like almost everything else in Linux, TCP/IP setup is a matter of preparing numerous configuration files (text files you can edit with any text editor). Most of these configuration files are in the /etc directory. The Red Hat installation program helps by hiding the details of the TCP/IP configuration files. Nevertheless, it’s better if you know the names of the files and their purposes so that you can edit the files manually, if necessary.
Cross Ref
The next few sections show you how to set up TCP/IP for an Ethernet LAN. Chapter 13 covers dial-up networking under Linux, including topics such as PPP. Appendix D discusses physical set up of Ethernet networks and types of Ehternet cards supported by Linux.
Before you look at TCP/IP setup, make sure your system’s Ethernet card is properly installed and detected by the Linux kernel. Also, you need to know the device names for the network devices.
Learning Network-Device Names
For most devices, Linux uses files in the /dev directory. The networking devices, however, have names defined internally in the kernel; no files for these devices exist in the /dev directory. Following are the common network-device names in Linux:
lo—The loopback device. This device is used for efficient handling of network packets sent from your system to itself (when, for example, an X client communicates with the X server on the same system).
eth0—The first Ethernet card or 802.11b wireless network card. If you have more Ethernet cards, they get device names eth1 , eth2 , and so on.
ppp0—The first serial port configured for a point-to-point link to another computer, using Point-to-Point Protocol (PPP). If you have more serial ports configured for PPP networking, they are assigned device names ppp1 , ppp2 , and so on.
sl0—The first serial port configured for Serial Line Internet Protocol (SLIP) networking. SLIP is used for establishing a point-to-point link to a TCP/IP network. If you use a second serial port for SLIP, it gets the device name sl1 . SLIP is not used much anymore; it has been superseded by PPP.
Insider Insight
You always have a loopback device (lo), whether or not you have a network. The loopback device passes data from one process to another without having to go out to a network. In fact, the whole point of the loopback device is to allow network applications to work, as long as the communicating processes are on the same system.
PPP is popular in dial-up networks, in which you use a modem to dial in to an Internet host (typically, a system at your work or your ISP) and establish a connection to the Internet. Chapter 13 covers this subject in detail.
If you want to see the names of installed network devices on your system, try the following command:
This command shows the network-device names, as well as statistics on the number of packets sent and received for a specific device.
Using Red Hat’s Network Configuration Tool
After you ensure that the Linux kernel is properly configured for TCP/IP, you have to make sure that the appropriate configuration files exist. Red Hat Linux includes a network configuration tool that enables you to configure various network interfaces on your system for TCP/IP networking. You can run the network configuration tool to add a new network interface or to alter information such as name servers and hostnames (you can also directly edit the configuration files listed in the “Using TCP/IP Configuration Files” section).
Log in as root and from the GNOME desktop, select Main Menu>Programs>System>Network Configuration to run the Network Configuration tool. The Network Configuration tool displays a tabbed dialog box, as shown in Figure 6-6.
You can configure various aspects of your network through the four tabs that appear along the top of the dialog box. Specifically, the tabs enable you to do the following:
Devices—Lets you add a new network interface, specify the IP address of the interface, and activate the interface. This information is stored in various files in the /etc/sysconfig directory.
Hardware— Lets you add a new hardware device such as an Ethernet card, modem, or an ISDN device. You can then provide information such as interrupt request (IRQ) and I/O port numbers, and DMA channels for the device.
DNS—Lets you enter the hostname for your system and the IP addresses of name servers. The name server addresses are stored in the /etc/resolv.conf file. The host name is stored in the HOSTNAME variable in the /etc/sysconfig/ network file.
Hosts—Shows you the current contents of the /etc/hosts file and lets you add, remove, or edit entries.
To configure the network interfaces, you need to assign IP addresses to each interface. If you are running a private network, you may use IP addresses in the range 192.168.0.0 to 192.168.255.255. (There are other ranges of addresses reserved for private networks, but this range should suffice for most needs.) For example, I use the 192.168.0.0 address for a small private network.
Testing the Network
After you run the Network Configuration tool, you may want to check whether or not the network is up and running. If you have not rebooted your system yet, you have to run /sbin/ifconfig to configure the Ethernet interface for your IP address. On a system whose IP address is 192.168.0.4, you would type the following command (you have to be logged in as root to do this):
Now, you should use the ping utility program to verify whether or not another system on your network is accessible. You need the IP address of another system on the network to use ping . On my PC, I might try the following:
If the ping command shows that other systems on your network are reachable, you can proceed to use other network programs, such as FTP and Telnet.
Using TCP/IP Configuration Files
Running the Red Hat network configuration tool may be enough to get TCP/IP configured on your system. You may want to be familiar with the configuration files, however, so that you can edit the files if necessary. For example, you can specify the name servers through the network configuration tool, but you may want to add an alternate name servers directly to the configuration file. To do so, you need to know about the /etc/resolv.conf file, which stores the IP addresses of name servers.
The following sections describe the basic TCP/IP configuration files.
/etc/hosts
The /etc/hosts text file contains a list of IP addresses and hostnames for your local network. In the absence of a name server, any network program on your system consults this file to determine the IP address that corresponds to a hostname.
Following is the /etc/hosts file from my system, showing the IP addresses and names of other hosts on my LAN:
As the example shows, each line in the file starts with an IP address, followed by the hostname for that IP address. You can have more than one hostname for a given IP address.
/etc/networks
/etc/networks is another text file that contains the names and IP addresses of networks. These network names are commonly used in the routing command ( /sbin/route ) to specify a network by name instead of by its IP address.
Don’t be alarmed if your Linux PC does not have the /etc/networks file. Your TCP/IP network works fine without this file. In fact, the Red Hat Linux installation program does not create a /etc/networks file.
/etc/host.conf
Linux uses a resolver library to obtain the IP address that corresponds to a hostname. The /etc/host.conf file specifies how names are resolved. A typical /etc/host.conf file might contain the following lines:
The entries in the /etc/host.conf file tell the resolver library what services to use (and in which order) to resolve names.
The order option indicates the order of services. The sample entry specifies that the resolver library should first consult the /etc/hosts file, then check the name server to resolve a name. In other words, this host.conf file says: “use static resolution prior to dynamic resolution.”
Insider Insight
The multi option determines whether or not a host in the /etc/hosts file can have multiple IP addresses. Hosts that have more than one IP address are called multihomed because the presence of multiple IP addresses implies that the host has several network interfaces (the host “lives” in several networks simultaneously).
/etc/resolv.conf
The /etc/resolv.conf file is another text file used by the resolver—a library that determines the IP address for a hostname. Following is a sample /etc/resolv.conf file:
The first line specifies your system’s domain name. The nameserver line provides the IP addresses of name servers for your domain. If you have multiple name servers, you should list them on separate lines. They are queried in the order in which they appear in the file.
If you do not have a name server for your network, you can safely ignore this file. TCP/IP should still work, even though you may not be able to refer to hosts by name. You do, however, have to make sure that you have a /etc/host.conf file that is set up to use the /etc/hosts file.
Insider Insight
If your system gets its IP address from a DHCP server, the DHCP client also receives the IP addresses of name servers as well as the domain name from the DHCP service. In this case, the DHCP client automatically creates a /etc/resolv.conf file with the name server information it obtains from the DHCP server.
/etc/hosts.allow
This file specifies which hosts are allowed to use the Internet services such as Telnet running on your system. As explained in the section “Understanding the xinetd Configuration Files,” the TCP wrapper consults the /etc/hosts.allow file before starting Internet services. It starts the service only if the entries in the hosts.allow file imply that the requesting host is allowed to use the services.
The entries in /etc/hosts.allow are in the form of a server : IP address format, where server refers to the name of the program providing a specific Internet service, and IP address identifies the host allowed to use that service. For example, if you want all hosts in your local network (which has the class C address 192.168.0.0) to access the Telnet service (which is provided by the in.telnetd program), add the following line in the /etc/hosts.allow file:
If you want to let all local hosts have access to all Internet services, you can use the ALL keyword and rewrite the line as follows:
Finally, to open all Internet services to all hosts, you can replace the IP address with ALL , as follows:
You can also use host names in place of IP addresses.
Insider Insight
To learn the detailed syntax of the entries in the /etc/hosts.allow file, type man hosts.allow at the Linux shell prompt.
/etc/hosts.deny
This file is just the opposite of /etc/hosts.allow —whereas hosts.allow specifies which hosts may access Internet services (such as T ELNET and FTP) on your system, the hosts.deny file identifies the hosts that must be denied services. As explained in the section “Understanding the xinetd Configuration Files,” the TCP wrapper consults the /etc/hosts.deny file if it does not find any rules in the /etc/hosts.allow file that apply to the requesting host. The TCP wrapper denies service if it finds in the hosts.deny file a rule that applies to the host.
The entries in /etc/hosts.deny file follow the same format as those in the /etc/hosts.allow file—they are in the form of a server : IP address format , where server refers to the name of the program providing a specific Internet service and IP address identifies the host allowed to use that service.
If you have already set up entries in the /etc/hosts.allow file to allow access to specific hosts, you can place the following line in /etc/hosts.deny to deny all other hosts access to any service on your system:
Insider Insight
To learn the detailed syntax of the entries in the /etc/hosts.deny file, type man hosts.deny at the Linux shell prompt.
/etc/nsswitch.conf
This file, known as the name service switch (NSS) file, specifies how services, such as the name resolver library, NIS, NIS+, and local configuration files such as /etc/hosts and /etc/shadow , interact. Newer versions of Linux that use GNU C Library version 2 (glibc 2) or later rely on the /etc/nsswitch.conf file to determine what takes precedence: a local configuration file or a service such as DNS or NIS (see Chapter 18 to learn more about DNS and NIS).
As an example, the following hosts entry in the /etc/nsswitch.conf file specifies that the resolver library should first try the /etc/hosts file , then try NIS+, and finally try DNS:
Insider Insight
You can learn more about the /etc/nsswitch.conf file by typing info libc «Name Service Switch» in a terminal window.
Configuring Networks at Boot Time
You want to start your network automatically every time you boot the system. For this to happen, you have to put the appropriate commands in one or more startup scripts. The init process runs immediately after Linux boots. The process consults the /etc/inittab file and executes various commands (typically, shell scripts), depending on the current run level. For example, in run level 3—the multiuser level— /etc/inittab specifies that init should run the script file /etc/rc.d/rc with the argument 3.
In run levels 3 and 5, the startup script ends up executing the /etc/rc.d/init.d/ network script to activate all networking interfaces. If you consult the /etc/rc.d/ init.d/network file , you will notice that network initialization is done by using another set of files in the /etc/sysconfig directory. The network activation script checks the variables defined in the /etc/sysconfig/network file to decide whether or not to activate the network. In /etc/sysconfig/network , you should see a line with the NETWORKING variable as follows:
The network is activated only if the NETWORKING variable is set to yes .
The /etc/rc.d/init.d/network script, in turn, executes a number of scripts in the /etc/sysconfig/network-scripts directory to activate specific net- work interfaces. For example, to activate the Ethernet interface eth0, the /etc/ sysconfig/network-scripts/ifup script is executed with /etc/sysconfig/ network-scripts/ifcfg-eth0 as the configuration file. Here is what a typical /etc/sysconfig/network-scripts/ifcfg-eth0 file contains:
As you can see, this file contains the network device name, as well as the IP address of the interface and several other TCP/IP parameters. The ONBOOT variable indicates whether this network interface should be activated when Linux boots. If your PC has an Ethernet card, you want to activate the interface at boot time; therefore, ONBOOT is set to yes .
The files in the /etc/sysconfig directory are created by the Red Hat Linux installation program as you install Linux and also by the Red Hat network configuration tool when you configure the network later on.
The /etc/sysconfig/network-scripts/ifup script essentially runs the following commands:
/sbin/ifconfig , to configure the specified network interface; in this case, the Ethernet card (eth0)
/sbin/route , to set up the routing table for the activated network interface