Capítulo 5. Configuração de rede

Índice

5.1. A infraestrutura de rede básica
5.1.1. O nome de domínio
5.1.2. A resolução de nome de máquina
5.1.3. O nome da interface de rede
5.1.4. O alcance de endereços de rede para a LAN
5.1.5. O suporte a dispositivos de rede
5.2. A configuração de rede moderna para desktop
5.2.1. Ferramentas GUI de configuração de rede
5.3. A ligação e configuração legacy de rede
5.4. O método de ligação de rede (legacy)
5.4.1. A ligação DHCP com a Ethernet
5.4.2. A ligação de IP estático com a Ethernet
5.4.3. A ligação PPP com o pppconfig
5.4.4. A ligação PPP alternativa com o wvdialconf
5.4.5. A ligação PPPoE com o pppoeconf
5.5. A configuração de rede básica com ifupdown (legacy)
5.5.1. A sintaxe de comando simplificada
5.5.2. A sintaxe básica de "/etc/network/interfaces"
5.5.3. A interface de rede loopback
5.5.4. A interface de rede servida por DHCP
5.5.5. A interface de rede com IP estático
5.5.6. A base da interface LAN wireless
5.5.7. A interface LAN wireless com WPA/WPA2
5.5.8. A interface LAN wireless com WEP
5.5.9. A ligação PPP
5.5.10. A ligação PPP alternativa
5.5.11. A ligação PPPoE
5.5.12. O estado de configuração de rede do ifupdown
5.5.13. A base da configuração de rede
5.5.14. O pacote ifupdown-extra
5.6. A configuração de rede avançada com ifupdown (legacy)
5.6.1. O pacote ifplugd
5.6.2. O pacote ifmetric
5.6.3. A interface virtual
5.6.4. A sintaxe de comando avançada
5.6.5. A estrofe de mapeamento
5.6.6. A configuração de rede comutável manualmente
5.6.7. Usar scripts com o sistema ifupdown
5.6.8. Mapeando com guessnet
5.7. A configuração de rede de baixo nível
5.7.1. Comandos iproute2
5.7.2. Operações de rede seguras de baixo nível
5.8. Optimização da rede
5.8.1. Encontrar o MTU óptimo
5.8.2. Definir o MTU
5.8.3. Optimização WAN TCP
5.9. Infraestrutura do netfilter
[Dica] Dica

For general guide to the GNU/Linux networking, read the Linux Network Administrators Guide.

5.1. A infraestrutura de rede básica

Vamos rever a infraestrutura de rede básica do sistema Debian moderno.

Tabela 5.1. Lista de ferramentas de configuração de rede

pacotes popcon tamanho tipo descrição
ifupdown * V:60, I:99 228 config::ifupdown ferramenta standard para activar e desactivar a rede (especificação da Debian)
ifplugd * V:0.4, I:0.9 244 , , gerir a rede com fios automaticamente
ifupdown-extra * V:0.04, I:0.2 124 , , script de testes de rede para melhorar o pacote "ifupdown"
ifmetric * V:0.02, I:0.10 100 , , define métricas de rota para uma interface de rede
guessnet * V:0.07, I:0.3 516 , , mapear o script para melhorar o pacote "ifupdown" via ficheiro "/etc/network/interfaces"
ifscheme * V:0.03, I:0.08 132 , , scripts de mapeamento para melhorar o pacote "ifupdown"
ifupdown-scripts-zg2 * V:0.00, I:0.04 232 , , scripts da interface Zugschlus para o método manual do ifupdown
network-manager * V:24, I:33 2628 config::NM NetworkManager (daemon): gere a rede automaticamente
network-manager-gnome * V:17, I:29 5616 , , NetworkManager (frontend do GNOME)
network-manager-kde * V:2, I:3 264 , , NetworkManager (frontend do KDE)
cnetworkmanager * V:0.05, I:0.2 208 , , NetworkManager (cliente de linha de comandos)
wicd * V:0.5, I:2 88 config::wicd gestor de rede com fios e sem fios (metapacote)
wicd-cli * V:0.04, I:0.2 128 , , gestor de rede com fios e sem fios (cliente de linha de comandos)
wicd-curses * V:0.15, I:0.4 236 , , gestor de rede com fios e sem fios (cliente Curses)
wicd-daemon * V:1.9, I:2 1780 , , gestor de rede com fios e sem fios (daemon)
wicd-gtk * V:1.6, I:2 772 , , gestor de rede com fios e sem fios (cliente GTK+)
iptables * V:27, I:99 1316 config::Netfilter ferramentas administrativas para packet filtering e NAT (Netfilter)
iproute * V:41, I:88 1044 config::iproute2 iproute2, IPv6 e outra configuração de rede avançada: ip(8), tc(8), etc
ifrename * V:0.2, I:0.6 236 , , renomear interfaces de rede baseado em vários critérios de estatística: ifrename(8)
ethtool * V:4, I:13 208 , , mostra ou altera as definições de um dispositivo Ethernet
iputils-ping * V:36, I:99 96 test::iproute2 test network reachability of a remote host by hostname or IP address (iproute2)
iputils-arping * V:0.6, I:6 36 , , test network reachability of a remote host specified by the ARP address
iputils-tracepath * V:0.4, I:2 72 , , rastreia o caminho de rede até uma máquina remota
net-tools * V:70, I:99 1016 config::net-tools conjunto de ferramentas de rede NET-3 (net-tools, configuração de rede IPv4): ifconfig(8) etc.
inetutils-ping * V:0.03, I:0.12 296 test::net-tools test network reachability of a remote host by hostname or IP address (legacy, GNU)
arping * V:0.5, I:3 104 , , test network reachability of a remote host specified by the ARP address (legacy)
traceroute * V:13, I:99 192 , , rastreia o caminho de rede até uma máquina remota (legacy, consola)
dhcp3-client * V:32, I:92 60 config::low-level Cliente DHCP
wpasupplicant * V:28, I:39 828 , , suporte de cliente para WPA e WPA2 (IEEE 802.11i)
wireless-tools * V:7, I:22 420 , , ferramentas para manipular Extensões Wireless do Linux
ppp * V:6, I:26 1016 , , ligação PPP/PPPoE com chat
pppoeconf * V:0.4, I:3 344 config::helper ajudante de configuração para ligação PPPoE
pppconfig * V:0.2, I:2 964 , , ajudante de configuração para ligação PPP com chat
wvdial * V:0.5, I:2 416 , , ajudante de configuração para ligação PPP com wvdial e ppp
mtr-tiny * V:2, I:26 120 test::low-level rastreia o caminho de rede até uma máquina remota (curses)
mtr * V:0.7, I:3 180 , , rastreia o caminho de rede até uma máquina remota (curses e GTK+)
gnome-nettool * V:2, I:33 2848 , , ferramentas para operações comuns de informação de rede (GNOME)
nmap * V:6, I:31 7112 , , mapeamento de rede / sondagem de portos (Nmap, consola)
zenmap * V:0.2, I:1.3 2400 , , mapeamento de rede / sondagem de portos (GTK+)
knmap * V:0.10, I:0.6 712 , , mapeamento de rede / sondagem de portos (KDE)
tcpdump * V:3, I:24 1020 , , analisador de tráfego de rede (Tcpdump, consola)
wireshark * V:1.4, I:9 2052 , , analisador de tráfego de rede (Wireshark, GTK+)
tshark * V:0.4, I:3 276 , , analisador de tráfego de rede (consola)
nagios3 * V:1.0, I:1.8 32 , , sistema de monitorização e gestão para máquinas, serviços e redes (Nagios)
tcptrace * V:0.05, I:0.4 436 , , produz um sumário das ligações a partir da saída do tcpdump
snort * V:0.6, I:0.8 1260 , , sistema flexível de detecção de intrusos na rede (Snort)
ntop * V:1.2, I:2 11124 , , mostra a utilização da rede num navegador web
dnsutils * V:14, I:90 412 , , clientes de rede disponibilizados com BIND: nslookup(8), nsupdate(8), dig(8)
dlint * V:0.4, I:6 96 , , check DNS zone information using nameserver lookups
dnstracer * V:0.11, I:0.5 92 , , rastreia uma cadeia de servidores DNS até à fonte

5.1.1. O nome de domínio

The naming for the domain name is a tricky one for the normal PC workstation users. The PC workstation may be mobile one hopping around the network or located behind the NAT firewall inaccessible from the Internet. For such case, you may not want the domain name to be a valid domain name to avoid name collision.

[Dica] Dica

When you use an invalid domain name, you need to spoof the domain name used by some programs such as MTA for their proper operation. See Secção 6.3.3, “A configuração do endereço de mail”.

According to rfc2606, "invalid" seems to be a choice for the top level domain (TLD) to construct domain names that are sure to be invalid from the Internet.

The mDNS network discovery protocol (Apple Bonjour / Apple Rendezvous, Avahi on Debian) uses "local" as the pseudo-top-level domain. Microsoft also seems to promote "local" for the TLD of local area network.

[Atenção] Atenção

If the DNS service on your LAN uses "local" as TLD for your LAN, it may interfare with mDNS.

Other popular choices for the invalid TLD seem to be "localdomain", "lan", "localnet", or "home" according to my incoming mail analysis.

5.1.2. A resolução de nome de máquina

The hostname resolution is currently supported by the NSS (Name Service Switch) mechanism too. The flow of this resolution is the following.

  1. The "/etc/nsswitch.conf" file with stanza like "hosts: files dns" dictates the hostname resolution order. (This replaces the old functionality of the "order" stanza in "/etc/host.conf".)
  2. The files method is invoked first. If the hostname is found in the "/etc/hosts" file, it returns all valid addresses for it and exits. (The "/etc/host.conf" file contains "multi on".)
  3. The dns method is invoked. If the hostname is found by the query to the Internet Domain Name System (DNS) identified by the "/etc/resolv.conf" file, it returns all valid addresses for it and exits.

O ficheiro "/etc/hosts" que associa endereços IP com nomes de máquinas contém o seguinte.

127.0.0.1 localhost
127.0.1.1 <host_name>.<domain_name> <host_name>

# As linhas seguintes são desejáveis para máquinas capazes de IPv6
::1     ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters
ff02::3 ip6-allhosts

Here the <host_name> in this matches the own hostname defined in the "/etc/hostname". The <domain_name> in this is the fully qualified domain name (FQDN) of this host.

[Dica] Dica

For <domain_name> of the mobile PC without the real FQDN, you may pick a bogus and safe TLD such as "lan", "home", "invalid", "localdomain", "none", and "private".

The "/etc/resolv.conf" is a static file if the resolvconf package is not installed. If installed, it is a symbolic link. Either way, it contains information that initialize the resolver routines. If the DNS is found at IP="192.168.11.1", it contains the following.

nameserver 192.168.11.1

The resolvconf package makes this "/etc/resolv.conf" into a symbolic link and manages its contents by the hook scripts automatically.

The hostname resolution via Multicast DNS (using Zeroconf, aka Apple Bonjour / Apple Rendezvous) which effectively allows name resolution by common Unix/Linux programs in the ad-hoc mDNS domain "local", can be provided by installing the libnss-mdns package. The "/etc/nsswitch.conf" file should have stanza like "hosts: files mdns4_minimal [NOTFOUND=return] dns mdns4" to enable this functionality.

5.1.3. O nome da interface de rede

The network interface name, e.g. eth0, is assigned to each hardware in the Linux kernel through the user space configuration mechanism, udev (see Secção 3.5.11, “O sistema udev”), as it is found. The network interface name is referred as physical interface in ifup(8) and interfaces(5).

In order to ensure each network interface to be named persistently for each reboot using MAC address etc., there is a record file "/etc/udev/rules.d/70-persistent-net.rules". This file is automatically generated by the "/lib/udev/write_net_rules" program, probably run by the "persistent-net-generator.rules" rules file. You can modify it to change naming rule.

[Cuidado] Cuidado

When editing the "/etc/udev/rules.d/70-persistent-net.rules" rules file, you must keep each rule on a single line and the MAC address in lowercase. For example, if you find "Firewire device" and "PCI device" in this file, you probably want to name "PCI device" as eth0 and configure it as the primary network interface.

5.1.4. O alcance de endereços de rede para a LAN

Let us be reminded of the IPv4 32 bit address ranges in each class reserved for use on the local area networks (LANs) by rfc1918. These addresses are guaranteed not to conflict with any addresses on the Internet proper.

Tabela 5.2. Lista de alcances de endereços de rede

Classe endereços de rede máscara de rede máscara de rede /bits # de sub-redes
A 10.x.x.x 255.0.0.0 /8 1
B 172.16.x.x — 172.31.x.x 255.255.0.0 /16 16
C 192.168.0.x — 192.168.255.x 255.255.255.0 /24 256

[Nota] Nota

If one of these addresses is assigned to a host, then that host must not access the Internet directly but must access it through a gateway that acts as a proxy for individual services or else does Network Address Translation(NAT). The broadband router usually performs NAT for the consumer LAN environment.

5.1.5. O suporte a dispositivos de rede

Although most hardware devices are supported by the Debian system, there are some network devices which require DSFG non-free external hardware drivers to support them. Please see Secção 9.7.8, “Drivers de hardware não-livres”.

5.2. A configuração de rede moderna para desktop

Debian squeeze systems can manage the network connection via management daemon software such as NetworkManager (NM) (network-manager and associated packages) or Wicd (wicd and associated packages).

  • Vêm com as suas próprias GUIs e programas de linha de comandos como as suas interfaces de utilizador.
  • Vêm com os seus próprios daemons como os seus sistemas de backend.
  • Permitem ligação fácil do seu sistema à Internet.
  • Permitem gestão fácil de configuração de redes com fio e sem fios.
  • Permitem-nos configurar a rede independentemente do pacote legacy ifupdown.
[Nota] Nota

Não use estas ferramentas de configuração de rede automáticas em servidores. Estas são destinadas principalmente para os utilizadores móveis em portáteis.

Estas ferramentas de configuração de rede modernas precisam de ser configuradas correctamente para evitar entrarem em conflito com o pacote legacy ifupdown e o seu ficheiro de configuração "/etc/network/interfaces".

[Nota] Nota

Some features of these automatic network configuration tools may suffer regressions. These are not as robust as the legacy ifupdown package. Check BTS of network-manager and BTS of wicd for current issues and limitations.

5.2.1. Ferramentas GUI de configuração de rede

Official documentations for NM and Wicd on Debian are provided in "/usr/share/doc/network-manager/README.Debian" and "/usr/share/doc/wicd/README.Debian", respectively.

Essencialmente, a configuração de rede para desktop é feita como se segue.

  1. Make desktop user, e.g. foo, belong to group "netdev" by the following (Alternatively, do it automatically via D-bus under modern desktop environments such as GNOME and KDE).

    $ sudo adduser foo netdev
  2. Mantenha a configuração de "/etc/network/interfaces" tão simples como o seguinte.

    auto lo
    iface lo inet loopback
  3. Reiniciar NM ou Wicd com o seguinte.

    $ sudo /etc/init.d/network-manager restart
    $ sudo /etc/init.d/wicd restart
  4. Configure a sua rede através de GUI.
[Nota] Nota

Only interfaces which are not listed in "/etc/network/interfaces" or which have been configured with "auto …" or "allow-hotplug …" and "iface … inet dhcp" (with no other options) are managed by NM to avoid conflict with ifupdown.

[Dica] Dica

If you wish to extend network configuration capabilities of NM, please seek appropriate plug-in modules and supplemental packages such as network-manager-openconnect, network-manager-openvpn-gnome, network-manager-pptp-gnome, mobile-broadband-provider-info, gnome-bluetooth, etc. The same goes for those of Wicd.

[Cuidado] Cuidado

These automatic network configuration tools may not be compatible with esoteric configurations of legacy ifupdown in "/etc/network/interfaces" such as ones in Secção 5.5, “A configuração de rede básica com ifupdown (legacy)” and Secção 5.6, “A configuração de rede avançada com ifupdown (legacy)”. Check BTS of network-manager and BTS of wicd for current issues and limitations.

5.3. A ligação e configuração legacy de rede

When the method described in Secção 5.2, “A configuração de rede moderna para desktop” does not suffice your needs, you should use the legacy network connection and configuration method which combines many simpler tools.

A ligação de rede legacy é específica para cada método (veja Secção 5.4, “O método de ligação de rede (legacy)”).

Existem 2 tipos de programas para a configuração de rede de baixo nível em Linux (veja Secção 5.7.1, “Comandos iproute2”).

  • Old net-tools programs (ifconfig(8), …) are from the Linux NET-3 networking system. Most of these are obsolete now.
  • New Linux iproute2 programs (ip(8), …) are the current Linux networking system.

Although these low level networking programs are powerful, they are cumbersome to use. So high level network configuration systems have been created.

The ifupdown package is the de facto standard for such high level network configuration system on Debian. It enables you to bring up network simply by doing , e.g., "ifup eth0". Its configuration file is the "/etc/network/interfaces" file and its typical contents are the following.

auto lo
iface lo inet loopback

auto eth0
iface eth0 inet dhcp

The resolvconf package was created to supplement ifupdown system to support smooth reconfiguration of network address resolution by automating rewrite of resolver configuration file "/etc/resolv.conf". Now, most Debian network configuration packages are modified to use resolvconf package (see "/usr/share/doc/resolvconf/README.Debian").

Helper scripts to the ifupdown package such as ifplugd, guessnet, ifscheme, etc. are created to automate dynamic configuration of network environment such as one for mobile PC on wired LAN. These are relatively difficult to use but play well with existing ifupdown system.

These are explained in detail with examples (see Secção 5.5, “A configuração de rede básica com ifupdown (legacy)” and Secção 5.6, “A configuração de rede avançada com ifupdown (legacy)”).

5.4. O método de ligação de rede (legacy)

[Cuidado] Cuidado

The connection test method described in this section are meant for testing purposes. It is not meant to be used directly for the daily network connection. You are advised to use them via NM, Wicd, or the ifupdown package (see Secção 5.2, “A configuração de rede moderna para desktop” and Secção 5.5, “A configuração de rede básica com ifupdown (legacy)”).

The typical network connection method and connection path for a PC can be summarized as the following.

Tabela 5.3. Lista de métodos de ligação de rede e caminhos de ligação

PC método de ligação caminho de ligação
Porto série (ppp0) PPP modem ⇔ POTS ⇔ ponto de acesso dial-up ⇔ ISP
Porto Ethernet (eth0) PPPoE/DHCP/Estático ⇔ BB-modem ⇔ serviço BB ⇔ ponto de acesso BB ⇔ ISP
Porto Ethernet (eth0) DHCP/Estático ⇔ LAN ⇔ router BB com with tradução de endereços de rede (NAT) (⇔ BB-modem …)

Aqui está um sumário do script de configuração para cada método de ligação.

Tabela 5.4. Lista de configurações de ligação de rede

método de ligação configuração pacote(s) backend
PPP pppconfig para criar conversa determinista pppconfig, ppp
PPP (alternativa) wvdialconf para criar conversa heurística ppp, wvdial
PPPoE pppoeconf para criar conversa determinista pppoeconf, ppp
DHCP descrito em "/etc/dhcp3/dhclient.conf" dhcp3-client
IP estático (IPv4) descrito em "/etc/network/interfaces" net-tools
IP estático (IPv6) descrito em "/etc/network/interfaces" iproute

A ligação de rede anónima significa o seguinte.

Tabela 5.5. Lista de ligações de rede anónimas

acrónimo significado
POTS serviço de antigo telefone simples
BB broadband
serviço BB e.g., the digital subscriber line (DSL), the cable TV, or the fiber to the premises (FTTP)
modem BB e.g., the DSL modem, the cable modem, or the optical network terminal (ONT)
LAN rede de área local
WAN rede de área alargada
DHCP protocolo de configuração dinâmico de máquina
PPP protocolo ponto-para-ponto
PPPoE protocolo ponto-para-ponto sobre Ethernet
ISP Provedor de serviço de Internet

[Nota] Nota

The WAN connection services via cable TV are generally served by DHCP or PPPoE. The ones by ADSL and FTTP are generally served by PPPoE. You have to consult your ISP for exact configuration requirements of the WAN connection.

[Nota] Nota

When BB-router is used to create home LAN environment, PCs on LAN are connected to the WAN via BB-router with network address translation (NAT). For such case, PC's network interfaces on the LAN are served by static IP or DHCP from the BB-router. BB-router must be configured to connect the WAN following the instruction by your ISP.

5.4.1. A ligação DHCP com a Ethernet

The typical modern home and small business network, i.e. LAN, are connected to the WAN(Internet) using some consumer grade broadband router. The LAN behind this router is usually served by the dynamic host configuration protocol (DHCP) server running on the router.

Just install the dhcp3-client package for the Ethernet served by the dynamic host configuration protocol (DHCP).

5.4.2. A ligação de IP estático com a Ethernet

Nenhuma acção especial necessária para a Ethernet servida pelo IP estático.

5.4.3. A ligação PPP com o pppconfig

O script de configuração pppconfig configura a ligação PPP interactivamente ao seleccionar o seguinte.

  • O número de telefone
  • O nome de utilizador do ISP
  • A palavra-passe do ISP
  • A velocidade da porta
  • A porta de comunicação do modem
  • O método de autenticação

Tabela 5.6. Lista de ficheiros de configuração para a ligação PPP com pppconfig

ficheiro função
/etc/ppp/peers/<nome_do_isp> O ficheiro de configuração gerado pelo pppconfig para um pppd específico para <nome_de_isp>
/etc/chatscripts/<nome_do_isp> O ficheiro de configuração gerado pelo pppconfig para conversa especifica com <nome_de_isp>
/etc/ppp/options O parâmetro de execução geral para o pppd
/etc/ppp/pap-secret Dados de autenticação para PAP (risco de segurança)
/etc/ppp/chap-secret Dados de autenticação para CHAP (mais seguro)

[Cuidado] Cuidado

The "<isp_name>" value of "provider" is assumed if pon and poff commands are invoked without arguments.

Você pode testar a configuração usando ferramentas de configuração de baixo nível como as seguintes.

$ sudo pon <nome_do_isp>
...
$ sudo poff <nome_do_isp>

Veja "/usr/share/doc/ppp/README.Debian.gz".

5.4.4. A ligação PPP alternativa com o wvdialconf

A different approach to using pppd(8) is to run it from wvdial(1) which comes in the wvdial package. Instead of pppd running chat(8) to dial in and negotiate the connection, wvdial does the dialing and initial negotiating and then starts pppd to do the rest.

O script de configuração wvdialconf configura a ligação PPP interactivamente apenas ao seleccionar o seguinte.

  • O número de telefone
  • O nome de utilizador do ISP
  • A palavra-passe do ISP

wvdial tem sucesso a criar a ligação na maioria dos casos e mantêm uma lista de dados de autenticação automaticamente.

Tabela 5.7. Lista de ficheiros de configuração para a ligação PPP com wvdialconf

ficheiro função
/etc/ppp/peers/wvdial O ficheiro de configuração gerado pelo wvdialconf para o pppd específico para wvdial
/etc/wvdial.conf O ficheiro de configuração gerado pelo wvdialconf
/etc/ppp/options O parâmetro de execução geral para o pppd
/etc/ppp/pap-secret Dados de autenticação para PAP (risco de segurança)
/etc/ppp/chap-secret Dados de autenticação para CHAP (mais seguro)

Você pode testar a configuração usando ferramentas de configuração de baixo nível como as seguintes.

$ sudo wvdial
...
$ sudo killall wvdial

Veja wvdial(1) e wvdial.conf(5).

5.4.5. A ligação PPPoE com o pppoeconf

When your ISP serves you with PPPoE connection and you decide to connect your PC directly to the WAN, the network of your PC must be configured with the PPPoE. The PPPoE stand for PPP over Ethernet. The configuration script pppoeconf configures the PPPoE connection interactively.

Os ficheiros de configuração são o seguinte.

Tabela 5.8. Lista de ficheiros de configuração para a ligação PPPoE com pppoeconf

ficheiro função
/etc/ppp/peers/dsl-provider O ficheiro de configuração gerado pelo pppoeconf para o pppd específico para pppoe
/etc/ppp/options O parâmetro de execução geral para o pppd
/etc/ppp/pap-secret Dados de autenticação para PAP (risco de segurança)
/etc/ppp/chap-secret Dados de autenticação para CHAP (mais seguro)

Você pode testar a configuração usando ferramentas de configuração de baixo nível como as seguintes.

$ sudo /sbin/ifconfig eth0 up
$ sudo pon dsl-provider
...
$ sudo poff dsl-provider
$ sudo /sbin/ifconfig eth0 down

Veja "/usr/share/doc/pppoeconf/README.Debian".

5.5. A configuração de rede básica com ifupdown (legacy)

The traditional TCP/IP network setup on Debian system uses ifupdown package as a high level tool. There are 2 typical cases.

These traditional setup methods are quite useful if you wish to set up advanced configuration (see Secção 5.5, “A configuração de rede básica com ifupdown (legacy)”).

The ifupdown package provides the standardized framework for the high level network configuration in the Debian system. In this section, we learn the basic network configuration with ifupdown with simplified introduction and many typical examples.

5.5.1. A sintaxe de comando simplificada

The ifupdown package contains 2 commands: ifup(8) and ifdown(8). They offer high level network configuration dictated by the configuration file "/etc/network/interfaces".

Tabela 5.9. Lista de comandos de configuração de rede básicos com ifupdown

comando acção
ifup eth0 bring up a network interface eth0 with the configuration eth0 if "iface eth0" stanza exists
ifdown eth0 bring down a network interface eth0 with the configuration eth0 if "iface eth0" stanza exists

[Atenção] Atenção

Do not use low level configuration tools such as ifconfig(8) and ip(8) commands to configure an interface in up state.

[Nota] Nota

Não existe nenhum comando ifupdown.

5.5.2. A sintaxe básica de "/etc/network/interfaces"

The key syntax of "/etc/network/interfaces" as explained in interfaces(5) can be summarized as the following.

Tabela 5.10. Lista de estrofes em "/etc/network/interfaces"

estrofe significado
"auto <nome_da_interface>" inicia a interface <nome_da_interface> no arranque do sistema
"allow-auto <nome_de_interface>" , ,
"allow-hotplug <nome_de_interface>" start interface <interface_name> when the kernel detects a hotplug event from the interface
Linhas começadas com "iface <nome_de_configuração> …" definem a configuração de rede <nome_de_configuração>
Linhas iniciadas com "mapping <nome_da_interface_global> " define mapping value of <config_name> for the matching <interface_name>
A linha começada com um cardinal "#" ignore as comments (end-of-line comments are not supported)
Uma linha terminada com uma barra inversa "\" estende a configuração para a próxima linha

Lines started with iface stanza has the following syntax.

iface <config_name> <address_family> <method_name>
 <option1> <value1>
 <option2> <value2>
 ...

For the basic configuration, the mapping stanza is not used and you use the network interface name as the network configuration name (See Secção 5.6.5, “A estrofe de mapeamento”).

[Atenção] Atenção

Do not define duplicates of the "iface" stanza for a network interface in "/etc/network/interfaces".

5.5.3. A interface de rede loopback

The following configuration entry in the "/etc/network/interfaces" file brings up the loopback network interface lo upon booting the system (via auto stanza).

auto lo
iface lo inet loopback

This one always exists in the "/etc/network/interfaces" file.

5.5.4. A interface de rede servida por DHCP

After prepairing the system by Secção 5.4.1, “A ligação DHCP com a Ethernet”, the network interface served by the DHCP is configured by creating the configuration entry in the "/etc/network/interfaces" file as the following.

allow-hotplug eth0
iface eth0 inet dhcp
 hostname "minha_máquina"

When the Linux kernel detects the physical interface eth0, the allow-hotplug stanza causes ifup to bring up the interface and the iface stanza causes ifup to use DHCP to configure the interface.

5.5.5. A interface de rede com IP estático

The network interface served by the static IP is configured by creating the configuration entry in the "/etc/network/interfaces" file as the following.

allow-hotplug eth0
iface eth0 inet static
 address 192.168.11.100
 netmask 255.255.255.0
 broadcast 192.168.11.255
 gateway 192.168.11.1
 dns-domain lan
 dns-nameservers 192.168.11.1

When the Linux kernel detects the physical interface eth0, the allow-hotplug stanza causes ifup to bring up the interface and the iface stanza causes ifup to use the static IP to configure the interface.

Aqui, eu assumi o seguinte.

  • Alcance de endereços IP da rede LAN: 192.168.11.0 - 192.168.11.255
  • Endereço IP da gateway: 192.168.11.1
  • Endereço IP do PC: 192.168.11.100
  • O pacote resolvconf: instalado
  • O nome de domínio: "lan"
  • Endereço IP do servidor DNS: 192.168.11.1

When the resolvconf package is not installed, DNS related configuration needs to be done manually by editing the "/etc/resolv.conf" as the following.

nameserver 192.168.11.1
domain lan
[Cuidado] Cuidado

The IP addresses used in the above example are not meant to be copied literally. You have to adjust IP numbers to your actual network configuration.

5.5.6. A base da interface LAN wireless

The wireless LAN (WLAN for short) provides the fast wireless connectivity through the spread-spectrum communication of unlicensed radio bands based on the set of standards called IEEE 802.11.

The WLAN interfaces are almost like normal Ethernet interfaces but require some network ID and encryption key data to be provided when they are initialized. Their high level network tools are exactly the same as that of Ethernet interfaces except interface names are a bit different like eth1, wlan0, ath0, wifi0, … depending on the kernel drivers used.

[Dica] Dica

The wmaster0 device is the master device which is an internal device used only by SoftMAC with new mac80211 API of Linux.

Aqui estão algumas palavras chave para lembrar para a WLAN.

Tabela 5.11. Lista de siglas para WLAN

acrónimo palavra completa significado
NWID ID de rede 16 bit network ID used by pre-802.11 WaveLAN network (very deprecated)
(E)SSID (Extended) Service Set Identifier network name of the Wireless Access Points (APs) interconnected to form an integrated 802.11 wireless LAN, Domain ID
WEP, (WEP2) Wired Equivalent Privacy 1st generation 64-bit (128-bit) wireless encryption standard with 40-bit key (deprecated)
WPA Wi-Fi Protected Access 2nd generation wireless encryption standard (most of 802.11i), compatible with WEP
WPA2 Wi-Fi Protected Access 2 3rd generation wireless encryption standard (full 802.11i), non-compatible with WEP

The actual choice of protocol is usually limited by the wireless router you deploy.

5.5.7. A interface LAN wireless com WPA/WPA2

You need to install the wpasupplicant package to support the WLAN with the new WPA/WPA2.

In case of the DHCP served IP on WLAN connection, the "/etc/network/interfaces" file entry should be as the following.

allow-hotplug ath0
iface ath0 inet dhcp
 wpa-ssid homezone
 # hexadecimal psk is encoded from a plaintext passphrase
 wpa-psk 000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f

Veja "/usr/share/doc/wpasupplicant/README.modes.gz".

5.5.8. A interface LAN wireless com WEP

You need to install the wireless-tools package to support the WLAN with the old WEP. (Your consumer grade router may still be using this insecure infrastructure but this is better than nothing.)

[Cuidado] Cuidado

Please note that your network traffic on WLAN with WEP may be sniffed by others.

In case of the DHCP served IP on WLAN connection, the "/etc/network/interfaces" file entry should be as the following.

allow-hotplug eth0
iface eth0 inet dhcp
 wireless-essid Home
 wireless-key1 0123-4567-89ab-cdef
 wireless-key2 12345678
 wireless-key3 s:password
 wireless-defaultkey 2
 wireless-keymode open

Veja "/usr/share/doc/wireless-tools/README.Debian".

5.5.9. A ligação PPP

You need to configure the PPP connection first as described before (see Secção 5.4.3, “A ligação PPP com o pppconfig”). Then, add the "/etc/network/interfaces" file entry for the primary PPP device ppp0 as the following.

iface ppp0 inet ppp
 provider <isp_name>

5.5.10. A ligação PPP alternativa

You need to configure the alternative PPP connection with wvdial first as described before (see Secção 5.4.4, “A ligação PPP alternativa com o wvdialconf”). Then, add the "/etc/network/interfaces" file entry for the primary PPP device ppp0 as the following.

iface ppp0 inet wvdial

5.5.11. A ligação PPPoE

For PC connected directly to the WAN served by the PPPoE, you need to configure system with the PPPoE connection as described before (see Secção 5.4.5, “A ligação PPPoE com o pppoeconf”). Then, add the "/etc/network/interfaces" file entry for the primary PPPoE device eth0 as the following.

allow-hotplug eth0
iface eth0 inet manual
 pre-up /sbin/ifconfig eth0 up
 up ifup ppp0=dsl
 down ifdown ppp0=dsl
 post-down /sbin/ifconfig eth0 down
# The following is used internally only
iface dsl inet ppp
 provider dsl-provider

5.5.12. O estado de configuração de rede do ifupdown

The "/etc/network/run/ifstate" file stores the intended network configuration states for all the currently active network interfaces managed by the ifupdown package are listed. Unfortunately, even if the ifupdown system fails to bring up the interface as intended, the "/etc/network/run/ifstate" file lists it active.

Unless the output of the ifconfig(8) command for an interface does not have a line like following example, it can not be used as a part of IPV4 network.

  inet addr:192.168.11.2  Bcast:192.168.11.255  Mask:255.255.255.0
[Nota] Nota

For the Ethernet device connected to the PPPoE, the output of the ifconfig(8) command lacks a line which looks like above example.

5.5.13. A base da configuração de rede

When you try to reconfigure the interface, e.g. eth0, you must disable it first with the "sudo ifdown eth0" command. This removes the entry of eth0 from the "/etc/network/run/ifstate" file. (This may result in some error message if eth0 is not active or it is configured improperly previously. So far, it seems to be safe to do this for the simple single user work station at any time.)

You are now free to rewrite the "/etc/network/interfaces" contents as needed to reconfigure the network interface, eth0.

Then, you can reactivate eth0 with the "sudo ifup eth0" command.

[Dica] Dica

You can (re)initialize the network interface simply by "sudo ifdown eth0;sudo ifup eth0".

5.5.14. O pacote ifupdown-extra

The ifupdown-extra package provides easy network connection tests for use with the ifupdown package.

  • O comando network-test(1) pode ser usado a partir da shell.
  • The automatic scripts are run for each ifup command execution.

The network-test command frees you from the execution of cumbersome low level commands to analyze the network problem.

The automatic scripts are installed in "/etc/network/*/" and performs the following.

  • Verificar a ligação de cabo de rede
  • Verificar o uso duplicado de endereço IP
  • Setup system's static routes based on the "/etc/network/routes" definition
  • Verificar se a gateway de rede está ao alcance
  • Record results in the "/var/log/syslog" file

This syslog record is quite useful for administration of the network problem on the remote system.

[Dica] Dica

The automatic behavior of the ifupdown-extra package is configurable with the "/etc/default/network-test". Some of these automatic checks slow down the system boot-up a little bit since it takes some time to listen for ARP replies.

5.6. A configuração de rede avançada com ifupdown (legacy)

The functionality of the ifupdown package can be improved beyond what was described in Secção 5.5, “A configuração de rede básica com ifupdown (legacy)” with the advanced knowledge.

The functionalities described here are completely optional. I, being lazy and minimalist, rarely bother to use these.

[Cuidado] Cuidado

If you could not set up network connection by information in Secção 5.5, “A configuração de rede básica com ifupdown (legacy)”, you make situation worse by using information below.

5.6.1. O pacote ifplugd

The ifplugd package is older automatic network configuration tool which can manage only Ethernet connections. This solves unplugged/replugged Ethernet cable issues for mobile PC etc. If you have NetworkManager or Wicd (see Secção 5.2, “A configuração de rede moderna para desktop”) installed, you do not need this package.

This package runs daemon and replaces auto or allow-hotplug functionalities (see Tabela 5.10, “Lista de estrofes em "/etc/network/interfaces"”) and starts interfaces upon their connection to the network.

Here is how to use the ifplugd package for the internal Ethernet port, e.g. eth0.

  1. Remove stanza in "/etc/network/interfaces": "auto eth0" or "allow-hotplug eth0".
  2. Keep stanza in "/etc/network/interfaces": "iface eth0 inet …" and "mapping …".
  3. instale o pacote ifplugd.
  4. Corra "sudo dpkg-reconfigure ifplugd".
  5. Put eth0 as the "static interfaces to be watched by ifplugd".

Agora, a configuração de rede funciona como deseja.

  • Upon power-on or upon hardware discovery, the interface is not brought up by itself.

  • Após encontrar o cabo Ethernet, a interface é activada.
  • Upon some time after unplugging the Ethernet cable, the interface is brought down automatically.
  • Upon plugging in another Ethernet cable, the interface is brought up under the new network environment.
[Dica] Dica

Os argumentos para o comando ifplugd(8) podem definir o seu comportamento tal como o atraso para reconfigurar interfaces.

5.6.2. O pacote ifmetric

O pacote ifmetric permite-nos manipular métricas de rotas à posteriori mesmo para DHCP.

O seguinte configura a interface eth0 para ser preferida sobre a interface wlan0.

  1. Instale o pacote ifmetric.
  2. Adicione uma linha de opção com "metric 0" logo por baixo da linha "iface eth0 inet dhcp".
  3. Adicione uma linha de opção com "metric 1" logo por baixo da linha "iface wlan0 inet dhcp".

The metric 0 means the highest priority route and is the default one. The larger metric value means lower priority routes. The IP address of the active interface with the lowest metric value becomes the originating one. See ifmetric(8).

5.6.3. A interface virtual

A single physical Ethernet interface can be configured as multiple virtual interfaces with different IP addresses. Usually the purpose is to connect an interface to several IP subnetworks. For example, IP address based virtual web hosting by a single network interface is one such application.

Por exemplo, vamos supor o seguinte.

  • A single Ethernet interface on your host is connected to a Ethernet hub (not to the broadband router).
  • O hub Ethernet esta ligado a ambos; Internet e rede LAN.
  • A rede LAN usa a sub-rede 192.168.0.x/24.
  • A sua máquina usa endereço IP servido por DHCP com a interface física eth0 para a Internet.
  • A sua máquina usa 192.168.0.1 com a interface virtual eth0:0 para a LAN.

As seguintes estrofes em "/etc/network/interfaces" configuram a sua rede.

iface eth0 inet dhcp
 metric 0
iface eth0:0 inet static
 address 192.168.0.1
 netmask 255.255.255.0
 network 192.168.0.0
 broadcast 192.168.0.255
 metric 1
[Cuidado] Cuidado

Although this configuration example with network address translation (NAT) using netfilter/iptables (see Secção 5.9, “Infraestrutura do netfilter”) can provide cheap router for the LAN with only single interface, there is no real firewall capability with such set up. You should use 2 physical interfaces with NAT to secure the local network from the Internet.

5.6.4. A sintaxe de comando avançada

The ifupdown package offers advanced network configuration using the network configuration name and the network interface name. I use slightly different terminology from one used in ifup(8) and interfaces(5).

Tabela 5.12. Lista de terminologia para dispositivos de rede

terminologia do manual a minha terminologia exemplos no texto seguinte descrição
nome da interface física nome da interface de rede lo, eth0, <nome_da_interface> nome dado pelo kernel do Linux (usando o mecanismo udev)
nome da interface lógica nome da configuração de rede config1, config2, <nome_da_configuração> name token following iface in the "/etc/network/interfaces"

Basic network configuration commands in Secção 5.5.1, “A sintaxe de comando simplificada” require the network configuration name token of the iface stanza to match the network interface name in the "/etc/network/interfaces".

Advanced network configuration commands enables separation of the network configuration name and the network interface name in the "/etc/network/interfaces" as the following.

Tabela 5.13. Lista de comandos avançados de configuração de rede com ifupdown

comando acção
ifup eth0=config1 torna activa a interface de rede eth0 com a configuração config1
ifdown eth0=config1 torna inactiva a interface de rede eth0 com a configuração config1
ifup eth0 bring up a network interface eth0 with the configuration selected by mapping stanza
ifdown eth0 bring down a network interface eth0 with the configuration selected by mapping stanza

5.6.5. A estrofe de mapeamento

We skipped explaining the mapping stanza in the "/etc/network/interfaces" in Secção 5.5.2, “A sintaxe básica de "/etc/network/interfaces"” to avoid complication. This stanza has the following syntax.

mapping <interface_name_glob>
 script <script_name>
 map <script_input1>
 map <script_input2>
 map ...

This provides advanced feature to the "/etc/network/interfaces" file by automating the choice of the configuration with the mapping script specified by <script_name>.

Vamos seguir a execução do seguinte.

$ sudo ifup eth0

When the "<interface_name_glob>" matches "eth0", this execution produces the execution of the following command to configure eth0 automatically.

$ sudo ifup eth0=$(echo -e '<script_entrada1> \n <script_entrada2> \n ...' | <nome_do_script> eth0)

Here, script input lines with "map" are optional and can be repeated.

[Nota] Nota

The glob for mapping stanza works like shell filename glob (see Secção 1.5.6, “Glob da shell”).

5.6.6. A configuração de rede comutável manualmente

Here is how to switch manually among several network configurations without rewriting the "/etc/network/interfaces" file as in Secção 5.5.13, “A base da configuração de rede” .

For all the network configuration you need to access, you create a single "/etc/network/interfaces" file as the following.

auto lo
iface lo inet loopback

iface config1 inet dhcp
 hostname "mymachine"

iface config2 inet static
 address 192.168.11.100
 netmask 255.255.255.0
 broadcast 192.168.11.255
 gateway 192.168.11.1
 dns-domain lan
 dns-nameservers 192.168.11.1

iface pppoe inet manual
 pre-up /sbin/ifconfig eth0 up
 up ifup ppp0=dsl
 down ifdown ppp0=dsl
 post-down /sbin/ifconfig eth0 down

# O seguinte é usado apenas internamente
iface dsl inet ppp
 provider dsl-provider

iface pots inet ppp
 provider provider

Please note the network configuration name which is the token after iface does not use the token for the network interface name. Also, there are no auto stanza nor allow-hotplug stanza to start the network interface eth0 automatically upon events.

Agora você está pronto para comutar a configuração de rede.

Let's move your PC to a LAN served by the DHCP. You bring up the network interface (the physical interface) eth0 by assigning the network configuration name (the logical interface name) config1 to it by the following.

$ sudo ifup eth0=config1
Password:
...

A interface eth0 está activa, configurada por DHCP e ligada a LAN.

$ sudo ifdown eth0=config1
...

A interface eth0 está inactiva e desligada da LAN.

Let's move your PC to a LAN served by the static IP. You bring up the network interface eth0 by assigning the network configuration name config2 to it by the following.

$ sudo ifup eth0=config2
...

The interface eth0 is up, configured with static IP and connected to LAN. The additional parameters given as dns-* configures "/etc/resolv.conf" contents. This "/etc/resolv.conf" is better manged if the resolvconf package is installed.

$ sudo ifdown eth0=config2
...

A interface eth0 está inactiva e desligada da LAN, outra vez.

Let's move your PC to a port on BB-modem connected to the PPPoE served service. You bring up the network interface eth0 by assigning the network configuration name pppoe to it by the following.

$ sudo ifup eth0=pppoe
...

A interface eth0 está activa, configurada com ligação PPPoE directamente ao ISP.

$ sudo ifdown eth0=pppoe
...

A interface eth0 está inactiva e desligada, outra vez.

Let's move your PC to a location without LAN or BB-modem but with POTS and modem. You bring up the network interface ppp0 by assigning the network configuration name pots to it by the following.

$ sudo ifup ppp0=pots
...

A interface ppp0 está activa e ligada à Internet com PPP.

$ sudo ifdown ppp0=pots
...

A interface ppp0 está inactiva e desligada da Internet.

You should check the "/etc/network/run/ifstate" file for the current network configuration state of the ifupdown system.

[Atenção] Atenção

You may need to adjust numbers at the end of eth*, ppp*, etc. if you have multiple network interfaces.

5.6.7. Usar scripts com o sistema ifupdown

The ifupdown system automatically runs scripts installed in "/etc/network/*/" while exporting environment variables to scripts.

Tabela 5.14. Lista de variáveis de ambiente passadas pelo sistema ifupdown

variável de ambiente valor passado
"$IFACE" nome físico (nome da interface) da interface a ser processada
"$LOGICAL" nome lógico (nome da configuração) da interface a ser processada
"$ADDRFAM" <address_family> of the interface
"$METHOD" <method_name> of the interface. (e.g., "static")
"$MODE" "start" if run from ifup, "stop" if run from ifdown
"$PHASE" as per "$MODE", but with finer granularity, distinguishing the pre-up, post-up, pre-down and post-down phases
"$VERBOSITY" indicates whether "--verbose" was used; set to 1 if so, 0 if not
"$PATH" command search path: "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
"$IF_<OPTION>" value for the corresponding option under the iface stanza

Here, each environment variable, "$IF_<OPTION>", is created from the name for the corresponding option such as <option1> and <option2> by prepending "$IF_", converting the case to the upper case, replacing hyphens to underscores, and discarding non-alphanumeric characters.

[Dica] Dica

See Secção 5.5.2, “A sintaxe básica de "/etc/network/interfaces"” for <address_family>, <method_name>, <option1> and <option2>.

The ifupdown-extra package (see Secção 5.5.14, “O pacote ifupdown-extra”) uses these environment variables to extend the functionality of the ifupdown package. The ifmetric package (see Secção 5.6.2, “O pacote ifmetric”) installs the "/etc/network/if-up.d/ifmetric" script which sets the metric via the "$IF_METRIC" variable. The guessnet package (see Secção 5.6.8, “Mapeando com guessnet”), which provides simple and powerful framework for the auto-selection of the network configuration via the mapping mechanism, also uses these.

[Nota] Nota

For more specific examples of custom network configuration scripts using these environment variables, you should check example scripts in "/usr/share/doc/ifupdown/examples/*" and scripts used in ifscheme and ifupdown-scripts-zg2 packages. These additional scripts have some overlaps of functionalities with basic ifupdown-extra and guessnet packages. If you install these additional scripts, you should customize these scripts to avoid interferences.

5.6.8. Mapeando com guessnet

Instead of manually choosing configuration as described in Secção 5.6.6, “A configuração de rede comutável manualmente”, you can use the mapping mechanism described in Secção 5.6.5, “A estrofe de mapeamento” to select network configuration automatically with custom scripts.

The guessnet-ifupdown(8) command provided by the guessnet package is designed to be used as a mapping script and provides powerful framework to enhance the ifupdown system.

  • You list test condition as the value for guessnet options for each network configuration under iface stanza.
  • Mapping choses the iface with first non-ERROR result as the network configuration.

This dual usage of the "/etc/network/interfaces" file by the mapping script, guessnet-ifupdown, and the original network configuration infrastructure, ifupdown, does not cause negative impacts since guessnet options only export extra environment variables to scripts run by the ifupdown system. See details in guessnet-ifupdown(8).

[Nota] Nota

When multiple guessnet option lines are required in "/etc/network/interfaces", use option lines started with guessnet1, guessnet2, and so on, since the ifupdown package does not allow starting strings of option lines to be repeated.

5.7. A configuração de rede de baixo nível

5.7.1. Comandos iproute2

Iproute2 commands offer complete low-level network configuration capabilities. Here is a translation table from obsolete net-tools commands to new iproute2 etc. commands.

Tabela 5.15. Tabela de tradução dos comandos obsoletos net-tools para os novos comandos iproute2

ferramentas de rede obsoletas novo iproute2 etc. manipulação
ifconfig(8) ip addr endereço de protoco (IP ou IPv6) num dispositivo
route(8) ip route entrada na tabela de rotas
arp(8) ip neigh entrada na cache ARP ou NDISC
ipmaddr ip maddr endereço multicast
iptunnel ip tunnel túnel sobre IP
nameif(8) ifrename(8) nomeia as interfaces de rede baseadas no endereço MAC
mii-tool(8) ethtool(8) Definições de dispositivo Ethernet

Veja ip(8) e Manual da Suite de Utilitários IPROUTE2.

5.7.2. Operações de rede seguras de baixo nível

Você pode usar comandos de rede de baixo nível como se segue em segurança pois eles não mudam a configuração de rede.

Tabela 5.16. Lista de comandos de rede de baixo nível

comando descrição
ifconfig mostra o estado de ligação e endereço das interfaces activas
ip addr show mostra o estado de ligação e endereço das interfaces activas
route -n mostra toda a tabela de rotas em endereços numéricos
ip route show mostra toda a tabela de rotas em endereços numéricos
arp mostra o conteúdo actual das tabelas de cache ARP
ip neigh mostra o conteúdo actual das tabelas de cache ARP
plog mostra o log do daemon ppp
ping yahoo.com verifica a ligação de Internet para "yahoo.com"
whois yahoo.com verifica quem registou "yahoo.com" na base de dados de domínios
traceroute yahoo.com rastreia a ligação Internet até "yahoo.com"
tracepath yahoo.com rastreia a ligação Internet até "yahoo.com"
mtr yahoo.com rastreia a ligação Internet até "yahoo.com" (repetidamente)
dig [@dns-server.com] example.com [{a|mx|any}] check DNS records of "example.com" by "dns-server.com" for a "a", "mx", or "any" record
iptables -L -n verifica o filtro de pacotes
netstat -a procura todos os portos abertos
netstat -l --inet procura portos a escutar
netstat -ln --tcp procura portos TCP a escutar (numérico)
dlint exemplo.com verifica a informação da zona DNS de "exemplo.com"

[Dica] Dica

Some of these low level network configuration tools reside in "/sbin/". You may need to issue full command path such as "/sbin/ifconfig" or add "/sbin" to the "$PATH" list in your "~/.bashrc".

5.8. Optimização da rede

A optimização de rede genérica está para além do objectivo desta documentação. Eu apenas toco em assuntos pertinentes às ligações de grau de consumidor.

Tabela 5.17. Lista de ferramentas de optimização de rede

pacotes popcon tamanho descrição
iftop * V:1.3, I:7 72 mostra informação da utilização de largura de banda numa interface de rede
iperf * V:0.5, I:3 200 ferramenta de medição da largura de banda do Protocolo Internet
apt-spy * V:0.17, I:1.7 204 escreve um ficheiro "/etc/apt/sources.list" baseado em testes de largura de banda
ifstat * V:0.2, I:1.2 88 InterFace STATistics Monitoring
bmon * V:0.2, I:0.9 188 monitor de largura de banda portável e estimador de taxas
ethstatus * V:0.10, I:0.7 84 script que mede rapidamente a transferência efectiva de um dispositivo de rede
bing * V:0.08, I:0.6 96 testador de largura de banda empírica estocástica
bwm-ng * V:0.2, I:1.2 152 monitor de largura de banda pequeno e simples baseado em consola
ethstats * V:0.05, I:0.3 52 monitor de estatísticas de Ethernet baseado em consola
ipfm * V:0.04, I:0.19 156 ferramenta de análise de largura de banda

5.8.1. Encontrar o MTU óptimo

The Maximum Transmission Unit (MTU) value can be determined experimentally with ping(8) with "-M do" option which sends ICMP packets with data size starting from 1500 (with offset of 28 bytes for the IP+ICMP header) and finding the largest size without IP fragmentation.

Por exemplo, tente o seguinte

$ ping -c 1 -s $((1500-28)) -M do www.debian.org
PING www.debian.org (194.109.137.218) 1472(1500) bytes of data.
From 192.168.11.2 icmp_seq=1 Frag needed and DF set (mtu = 1454)

--- www.debian.org ping statistics ---
0 packets transmitted, 0 received, +1 errors

Tente 1454 em vez de 1500

Você vê ping(8) com sucesso com 1454.

This process is Path MTU (PMTU) discovery (RFC1191) and the tracepath(8) command can automate this.

[Dica] Dica

The above example with PMTU value of 1454 is for my previous FTTP provider which used Asynchronous Transfer Mode (ATM) as its backbone network and served its clients with the PPPoE. The actual PMTU value depends on your environment, e.g., 1500 for the my new FTTP provider.

Tabela 5.18. Regras básicas para o valor MTU óptimo

ambiente de rede MTU rationale
Ligação Dial-up (IP: PPP) 576 standard
Ligação Ethernet (IP: DHCP ou fixo) 1500 standard e predefinido
Ligação Ethernet (IP: PPPoE) 1492 (=1500-8) 2 bytes for PPP header and 6 bytes for PPPoE header
Ethernet link (ISP's backbone: ATM, IP: DHCP or fixed) 1462 (=48*31-18-8) author's speculation: 18 for Ethernet header, 8 for SAR trailer
Ethernet link (ISP's backbone: ATM, IP: PPPoE) 1454 (=48*31-8-18-8) see "Optimal MTU configuration for PPPoE ADSL Connections" for rationale

Adicionalmente a estas regras básicas, você deve saber o seguinte.

  • Any use of tunneling methods (VPN etc.) may reduce optimal MTU further by their overheads.
  • O valor MTU não deve exceder o valor PMTU determinado experimentalmente.
  • O maior valor MTU é geralmente melhor quando são conhecidas outras limitações.

5.8.2. Definir o MTU

Aqui estão exemplos para definir o valor MTU desde a sua predefinição 1500 até 1454.

For the DHCP (see Secção 5.5.4, “A interface de rede servida por DHCP”), you can replace pertinent iface stanza lines in the "/etc/network/interfaces" with the following.

iface eth0 inet dhcp
 hostname "mymachine"
 pre-up /sbin/ifconfig $IFACE mtu 1454

For the static IP (see Secção 5.5.5, “A interface de rede com IP estático”), you can replace pertinent 'iface' stanza lines in the "/etc/network/interfaces" with the following.

iface eth0 inet static
 address 192.168.11.100
 netmask 255.255.255.0
 broadcast 192.168.11.255
 gateway 192.168.11.1
 mtu 1454
 dns-domain lan
 dns-nameservers 192.168.11.1

For the direct PPPoE (see Secção 5.4.5, “A ligação PPPoE com o pppoeconf”), you can replace pertinent "mtu" line in the "/etc/ppp/peers/dsl-provider" with the following.

mtu 1454

The maximum segment size (MSS) is used as an alternative measure of packet size. The relationship between MSS and MTU are the following.

  • MSS = MTU - 40 para IPv4
  • MSS = MTU - 60 para IPv6
[Nota] Nota

The iptables(8) (see Secção 5.9, “Infraestrutura do netfilter”) based optimization can clamp packet size by the MSS and is useful for the router. See "TCPMSS" in iptables(8).

5.8.3. Optimização WAN TCP

The TCP throughput can be maximized by adjusting TCP buffer size parameters as described in "TCP Tuning Guide" and "TCP tuning" for the modern high-bandwidth and high-latency WAN. So far, the current Debian default settings serve well even for my LAN connected by the fast 1G bps FTTP service.

5.9. Infraestrutura do netfilter

Netfilter provides infrastructure for stateful firewall and network address translation (NAT) with Linux kernel modules (see Secção 3.5.12, “A inicialização de módulos do kernel”).

Tabela 5.19. Lista de ferramentas de firewall

pacotes popcon tamanho descrição
iptables * V:27, I:99 1316 ferramentas de administração para o netfilter
iptstate * V:0.14, I:0.9 152 continuously monitor netfilter state (similar to top(1))
shorewall-perl * V:0.15, I:0.5 76 Shoreline Firewall, netfilter configuration file generator (Perl-based, recommended for lenny)
shorewall-shell * I:1.9 76 Shoreline Firewall, netfilter configuration file generator (shell-based, alternative for lenny)

Main user space program of netfilter is iptables(8). You can manually configure netfilter interactively from shell, save its state with iptables-save(8), and restore it via init script with iptables-restore(8) upon system reboot.

Scripts de ajuda de configuração como o shorewall facilitam este processo.

Veja documentação em http://www.netfilter.org/documentation/ (ou em "/usr/share/doc/iptables/html/").

[Dica] Dica

Although these were written for Linux 2.4, both iptables(8) command and netfilter kernel function apply for current Linux 2.6.