preloader
  • Home
  • Maximizing Connectivity: Utilizing Two Internet Links Simultaneously

Highly available Internet

blog-thumb

📖 Estimated reading time: 16 min


Using 2 Internet providers on the same router can be essential for those who work from home.

This saves the user from having to manually disconnect from one WiFi network and connect to another, for example.

How do I use 2 internet connections at the same time?

This post was originally written in Portuguese. The translation into English is still in progress.

This type of configuration is called MultiWAN, and it allows the internet links to operate in Load Balancer mode, thus achieving better performance, and also has failover capability for greater availability, because if one of the links goes down, the internet will continue to work by automatically switching the links.

WARNING: This post is long and contains a lot of technical information.

In this article we will cover the following items:

- MultiWAN Load Balancer e Failover

- Smart Queue Management

- Configurações do OpenWRT

Linux OpenWRT

OpenWRT is a customizable Linux distribution designed to replace the standard firmware of wireless routers (WiFi), which are usually proprietary and don’t allow for much customization.


MultiWAN Load Balancer and Failover

There are 3 ways to achieve this.

Click to see more.


The Noob Way

Just buy a Dual Wan Router Redmi AX-5400 and connect the cables from each internet modem to the WAN1 and WAN2 ports.

🍰 This is the easy way, where there aren’t many configurations to be made. Just connect the cables and you’re done.

💰💰💰 The investment cost is average, and in most cases it pays off.



The Pro Way

Use a dedicated firewall, such as FortiGate-60D or even a MikroTik hAP ac2.

😎 This mode requires manual configuration, and for those who are not used to working with professional firewalls, there is a reasonable learning curve, especially in order to take advantage of all the equipment’s features.

💰💰💰💰💰💰 The cost of investing in such a firewall varies from moderate to high.



The Expert Way

Using OpenWRT with MWAN3. If you already have an OpenWRT-compatible router (mine is an Archer C7), all you have to do is configure it.

🤓 This method offers a great deal of control over the behavior of the links.

💰 Can cost you nothing if you already have a compatible router.



In this article, we’ll do everything the expert way, because it’s more fun and you learn more!



Setting up OpenWRT

Luckily for us, mwan3 is already practically configured, which saves a lot of time and drastically reduces the learning curve. We only need to make a few minor adjustments.


Topology

Each Internet Service Provider (ISP) has a router suitable for the type of internet link contracted (Fiber, Cable, ADSL, etc.).

In my environment, I have 2 fiber optic links (FTTH):

- Router 1 – 300Mbp/s link (ISP 1)

- Router 2 – 400Mbp/s link (ISP 2)


🌐 I ended up signing a second fiber optic link because the cost is relatively low, and the benefit of being able to work without interruptions is enormous.


The version of OpenWRT software in use is as follows:

*OpenWrt 22.03.3 r20028-43d71ad93e / LuCI openwrt-22.03 branch git-22.361.69894-438c598*

The modem running OpenWRT is a TP-Link Archer C7 v5.


Local Network

Each ISP router will need to be connected to a WAN port, which represents the internet links.

  • Router 1
    • ISP1
      • WAN
        • IP: 10.128.25.1
        • Mask: 255.255.255.0
        • Gateway: 10.128.25.254
        • WiFi & DHCP: Disabled
  • Router 2
    • ISP2
      • WANB
        • IP: 10.128.20.1
        • Mask: 255.255.255.0
        • Gateway: 10.128.20.254
        • WiFi & DHCP: Disabled

The local network will be the LAN, where the DHCP service will work and where we will administer OpenWRT.


  • Router TP-Link
    • LAN
      • Local Network
        • IP: 10.128.15.1
        • WiFi & DHCP: Enabled
        • IPv6 assignment length: Disabled
        • RA-Service: Disabled
        • DHCPv6-Service: Disabled



Switch Ports
TP-Link Archer C7 v5 running OpenWRT: Switch ports that should be used


In short, the interfaces of the TP-Link router should be used as follows:

- Internet: ISP 1 (WAN)

- Ethernet 1: Reassigned to WANB (ISP 2)

- Ethernet 4: LAN


Note:

Different subnets must be used on each network segment in this topology to avoid routing problems.


Important

Avoid using the spare RJ45 switch ports of your Internet Service Provider (ISP) routers. Connect only one port of each ISP1/ISP2 router to the router running OpenWRT.

As these ISP-supplied devices are very simple and do not have advanced control methods, 2 network cables connected between the same ISP router switch and the OpenWRT router could cause a loop in the network, causing everything to stop working.


☑️ To find out how to set up a WiFi network in OpenWRT, see this link.


👉 To avoid conflicts, disable the DHCPv4 and WiFi services on the ISP’s routers. The DHCPv6 service can remain active.

I recommend that you change the subnet and IPs of the ISP’s routers to something similar to the one presented in this article.


Tip:

If your ISP router does not have an option to disable DHCPv4, use the following trick:

🔸 Set the IPv4 range to just 1 IP (e.g. 10.128.25.100 to 10.128.25.100), and reserve this IP for a Mac Address that doesn’t exist on the network (ff:ff:ff:ff:ff:ff).

▪️ With this trick, the ISP’s router won’t be able to deliver IPv4.



Router topology
Topology

Update:

I recently replaced my Archer C7 with an Archer C6. This may sound like I downgraded the router, but in fact it was the opposite.

- The Archer C7 has a Qualcomm 1-core / 1-thread CPU.

- The Archer C6 has a Mediatek 2-core / 4-thread CPU.


Basic settings

I did a clean installation of OpenWRT. In other words, nothing was configured yet. This avoids a lot of problems, especially if you’re used to manually editing OpenWRT configuration files.

So that you can find your way around, the flow of the menus is indicated with the character “>”.

Tip: Before you start, make sure you have connected the computer you will be using to configure OpenWRT via cable. Configure a static IP on the network interface that is part of the same subnet that you will use for OpenWRT. Example static IP for the PC: 10.128.15.2/24.

[1] Hostname

System > System

  • Hostname: OpenWRT
  • Description: Escritorio
  • Timezone: America/Sao_Paulo

[2] LAN IP

Network > Interfaces > LAN

  • Static
    – IP: 10.128.15.1/24
    – GW: Nenhum
  • Desativar “Use default gateway”

[3] Ativar o DHCP

Network > Interfaces > LAN > DHCP Server

Aqui você pode configurar uma faixa de endereçamento, que o DHCP irá entregar para os clientes conectados.

  • Start: 100
  • Limit: 50
  • Lease: 24h

Neste exemplo, o DHCP entregará IPs na faixa entre 10.128.15.100-10.128.15.150.

  • Se você não entende muito de rede, saiba que o limite deve ser até 254.

[4] DNS Forwarder

Network > DHCP and DNS > DNS forwardings

Eu utilizo o OpenDNS Family, que é gratuito e protege um pouco contra acessos a destinos inadequados.

  • 208.67.222.123
  • 208.67.220.123

[5] Instalar os pacotes necessários no OpenWRT

Recomendo que faça esta parte via CLI. Acesse por SSH o seu OpenWRT e digite os seguintes comandos:

opkg update
opkg install mwan3
opkg install luci-app-mwan3
opkg install iptables-nft
opkg install ip6tables-nft
reboot

- Sim, você precisa fazer um reboot aqui, para evitar perder os acessos ao OpenWRT.


Smart Queue Management (SQM)

Este pacote auxilia no controle de latência. Veremos sua configuração mais adiante. Por enquanto faça apenas a instalação.

opkg update
opkg install luci-app-sqm
opkg install jq
reboot

Faça outro reboot para carregar os módulos do kernel que foram instalados.


Configuração de Switch do OpenWRT

[1] Configuração do Switch

Network > Switch

Como o Archer C7 não possui 2 interfaces WAN, precisamos redesignar uma das interfaces LAN para que ela opere da mesma forma que a interface WAN dedicada.


Nota: 

Alguns roteadores não possuem a opção Switch (por exemplo o Archer C6). Caso seja seu caso, não se preocupe. Apenas pule esta parte e vá direto ao item “2”.

VLAN Interfaces

Iremos converter a interface LAN 1 (Ethernet 1) para a interface WANB (ISP 2). Não altere este nome, pois ele é pré-configurado no MWAN3.

  • A VLAN 1 não pode ser utilizada, pois ela é utilizada na LAN para administração do OpenWRT. A designação das VLANS ficará da seguinte forma:

    • WAN
      • VLAN 2
    • WANB (antiga LAN 1)
      • VLAN 3

[2] Configuração da primeira interface WAN

Network > Interfaces

Certifique-se de sempre usar lowercase ao criar as interfaces WANB e WANB6, para que a pré-configuração do mwan3 funcione de primeira.


Os nomes e configurações das interfaces WAN ficarão da seguintes forma:

  • wan

    • Protocol: Static address
    • Device: eth0.2
    • IP: 10.128.25.1
    • Netmask: 255.255.255.0
    • Gateway: 10.128.25.254
    • Use default gateway: marcado.
    • Gateway metric: 10 (configure também uma métrica de 30 para a interface wan6)
    • Firewall settings: Associar a zona wan.
    • DHCP Server: Ignore interface

  • wanb

    • Crie uma interface chamada wanb e faça as configurações a seguir.

      • Protocol: Static address
      • Device: eth0.3
      • IP: 10.128.20.1
      • Netmask: 255.255.255.0
      • Gateway: 10.128.20.254
      • Use default gateway: marcado.
      • Gateway metric: 20 (configure também uma métrica de 40 para a interface wanb6)
      • Firewall settings: Associar a zona wan.

  • wanb6

    • Crie uma interface chamada wanb6 e defina a mesma como DHCPv6 client.

      • Device: eth0.3
      • Request IPv6-address: try
      • Use default gateway: marcado
      • Use DNS servers advertised by peer: marcado
      • Use gateway metric: 40
      • IPv6 source routing: desativado
      • Delegate IPv6 prefixes: marcado
      • IPv6 assignment length: desativado
      • Firewall settings: Associar a zona wan.

  • – Para criar novas interfaces, basta clicar no botão “Add new interface”.

[3] Faça mais um reboot do OpenWRT, a fim de verificar se todas as configurações realizadas e interfaces irão inicializar corretamente.


Bridge

Vá para Network > Interfaces > Devices > br-lan. Certifique-se de que as interfaces WAN, WAN6, WANB e WANB6 não fazem parte da bridge br-lan.


Verificando a Conectividade

Via CLI, verifique se a configuração foi realizada corretamente e se existe comunicação através dos ISP Routers:

Comunicação local com os ISP Routers:

root@openwrt:~# ping -c3 10.128.25.254
PING 10.128.25.254 (10.128.25.254): 56 data bytes
64 bytes from 10.128.25.254: seq=0 ttl=64 time=0.659 ms
64 bytes from 10.128.25.254: seq=1 ttl=64 time=0.514 ms
64 bytes from 10.128.25.254: seq=2 ttl=64 time=0.522 ms
--- 10.128.25.254 ping statistics ---
3 packets transmitted, 3 packets received, 0% packet loss
round-trip min/avg/max = 0.514/0.565/0.659 ms
root@openwrt:~# ping -c3 10.128.20.254
PING 10.128.20.254 (10.128.20.254): 56 data bytes
64 bytes from 10.128.20.254: seq=0 ttl=64 time=2.552 ms
64 bytes from 10.128.20.254: seq=1 ttl=64 time=0.622 ms
64 bytes from 10.128.20.254: seq=2 ttl=64 time=0.585 ms
--- 10.128.20.254 ping statistics ---
3 packets transmitted, 3 packets received, 0% packet loss
round-trip min/avg/max = 0.585/1.253/2.552 ms

Rotas e métricas para as interfaces WAN:

root@openwrt:~# ip route show
default via 10.128.25.254 dev eth0.2 proto static metric 10
default via 10.128.20.254 dev eth0.3 proto static metric 20

Teste o acesso a internet através das interfaces VLAN configuradas:

root@openwrt:~# ping -c3 -I eth0.2 www.google.com
PING www.google.com (2800:3f0:4004:803::2004): 56 data bytes
64 bytes from 2800:3f0:4004:803::2004: seq=0 ttl=58 time=4.922 ms
root@openwrt:~# ping -c3 -I eth0.3 www.google.com
PING www.google.com (2800:3f0:4004:803::2004): 56 data bytes
64 bytes from 2800:3f0:4004:803::2004: seq=0 ttl=58 time=4.922 ms

Dica: 

Caso algum dos seus roteadores ISP não fornecer IPv6 por DHCPv6, não entre em pânico. Apenas desative no mwan3 a interface correspondente (wan6 ou wanb6).

Não é obrigatório a utilização de IPv6 em sua LAN. Os acessos para destinos públicos que utilizam IPv6 continuarão funcionando, pois seu ISP saberá como rotear o caminho até lá.


Configuração de IPv6

Arquiteturas com múltiplos links internet podem apresentar problemas ao rotear endereços IPv6. Existem várias formas de lidar com isso. Porém, neste artigo iremos utilizar o método que costuma funcionar melhor para usuários domésticos.

Não irei entrar no mérito referente a “IPv6 não precisa de NAT”.

Por questões técnicas o mwan3 precisa sim de NAT6, especialmente quando se trata de usuários domésticos, que não tem acesso a alguns recursos que os ISP apenas oferecem para empresas (BGP por exemplo). Para piorar a situação, alguns ISP não respeitam a RFC de implementação do IPv6, o que torna tudo ainda mais complexo.

[1] Configuração do Firewall

Habilite o mascaramento de IPv6 na zona upstream.

uci set firewall.@zone[1].masq6="1"
uci commit firewall
/etc/init.d/firewall restart

[2] Configuração da Rede WAN6.

Desative o roteamento de origem IPv6 na interface upstream.

uci set network.wan6.sourcefilter="0"
uci set network.wanb6.sourcefilter="0"
uci commit network
/etc/init.d/network restart

Verifique seus acessos via IPv6:

https://top.nic.br/connection/

http://test-ipv6.com/


Troubleshooting

Esta seção aborda problemas comuns.


VLANs

Em caso de problemas nas interfaces, verifique se a VLAN da WANB/WANB6 foi realmente criada. Já aconteceu comigo da VLAN associada a WANB/WANB6 (aquela que foi redesignada a partir da interface Ethernet 1) desaparecer, e foi necessário remover e refazer esta parte da configuração.

Para remover a configuração de device com falha, faça este caminho:

Network > Interfaces > Devices > eth0.3 > Unconfigure

Device not found

Depois remova as interfaces WANB e WANB6 e reconfigure as mesmas.


Problemas com IPv6

Em caso de problemas de roteamento com IPv6, verifique a vizinhança IPv6, as tabelas de roteamento e o status das interfaces.

root@openwrt:~# ip neigh show
root@openwrt:~# ip -6 route
root@openwrt:~# ifstatus wan6

Verifique as informações de IPv6 do roteador do ISP afetado, e utilize estas informações para configurar corretamente a interface WAN6 ou WANB6 (a que estiver com problemas de roteamento v6).


Configuração do MWAN3

[1] Configurar o MWAN3

Como mencionado anteriormente, o mwan3 já vem praticamente configurado, necessitando de pequenos ajustes.

Network > MultiWAN Manager > Interface

Observe que algumas interfaces estarão desativadas.

MultiWAN Manager

Ative as interfaces desativadas, clicando em Edit e posteriormente em Enabled.

Altere também o parâmetro Tracking reliability para “2”.

Os IPs de rastreamento de disponibilidade dos links internet podem necessitar ser ajustados. No meu caso, eu configurei desta forma:

  • Tracking hostname or IP address:

    • wan
      • Padrão do mwan3
    • wan6
      • Padrão do mwan3
    • wanb
      • Padrão do mwan3
    • wanb6
      • Padrão do mwan3

Caso queira, você pode utilizar outros IPs para fazer os testes de disponibilidade dos ISP.

[2] Verificar o status do MultiWAN

Status > MultiWAN Manager

MultiWAN overview

Para entender melhor o que está acontecendo a nível de sistema, rode os seguintes comandos via CLI:

iptables -t mangle -L
ip rule show
ip -4 route list table 1-250
ip route show table 1
ip route show table 2
ip route show table (...)
ip -6 route show

Todos os detalhes de status podem ser visualizados no menu:

Status > MultiWAN Manager > Troubleshooting

[3] Alteração no TTL dos links internet

Network > MultiWAN Manager > Interface

Este item pode necessitar de ajustes, dependendo do delay dos seus ISP. Você deve experimentar um pouco até encontrar os valores ideais. No meu cenário, eu não mudei nada. Deixei os valores default.


Importante:

Em alguns casos, o IP de destino pode começar a limitar a quantidade de requisições ICMP, fazendo com que o mwan3 entenda que o ISP está indisponível.

Logs

Caso você tenha problemas para aferir a disponibilidade do ISP, tente configurar o rastreamento com IPs diferentes. Diminua também o valor do Tracking reliability para “1”. Isso irá diminuir o tráfego ICMP para o ISP e distribuirá melhor as informações nas tabelas de roteamento.

Exemplo de tracking hostname or IP address:

Altere também a quantidade e o intervalo entre os testes de disponibilidade. Exemplo:

  • Ping count: 1
  • Ping timeout: 5
  • Ping interval: 10

Exemplo alternativo de rastreamento de disponibilidade dos links internet:

WAN Tracking

WANB Tracking

Para informação, estes são os IPv4 padrão usados no rastreio.

Default IP Tracking


Testando o MultiWAN

É importante entender alguns itens aqui.

- O multiwan é uma solução ativo-ativo para acesso a internet utilizando 2 ou mais ISPs.

- O multiwan não é um agregador de links. Ou seja, ele não irá aumentar sua banda internet. Cada acesso à internet estabelece uma sessão, e cada sessão poderá sair por um ou outro link de internet fornecido pelos seus ISP, fazendo assim um balanceamento de carga.

- Caso um link internet fique indisponível, automaticamente o mesmo será removido do balanceamento de carga, até que esteja disponível novamente.

- Um acesso HTTP padrão estabelece uma sessão, e por isso não é esperado que um download via web ocorra de forma mais rápida ao qual você já está habituado.

- Para gerenciadores de download (GetRight) ou protocolos que estabelecem múltiplas sessões (Torrent), pode ser experimentado um aumento de banda, pois neste caso ambos links internet serão utilizados durante o download. O speedtest.net pode utilizar múltiplas sessões em algumas situações.

Velocidade

Será que fica bom usar 2 links de internet ao mesmo tempo? Eu diria que fica interessante!

Speed Test

Gráficos

Podemos observar que cada link de internet tem um consumo diferente de banda.

Graphics

Teste de Disponibilidade

Desligue o roteador do ISP 1, e verifique se você ainda conseguirá navegar na internet. Observe que o tempo de chaveamento está relacionado com o intervalo dos testes de disponibilidade que você configurou.

Após a validação, ligue o roteador do ISP 1, espere o mwan3 reconhecer que o serviço está operacional, e desligue o roteador do ISP2.

Você pode acompanhar o status indo em:

Status > MultiWAN Manager

Simples assim. Temos balanceamento de carga e failover automático!

Minion Gamer

Minion Gamer


Logs do OpenWRT

Status > System Logs

Procure nos logs mensagens de erro que possam indicar que alguma configuração não foi feita corretamente.

Sun Apr 9 17:33:49 2023 user.info mwan3track[19143]: Check (ping) success for target "142.250.78.227" on interface wan (eth0.2). Current score: 0
Sun Apr 9 17:33:50 2023 user.info mwan3track[19145]: Check (ping) success for target "8.8.8.8" on interface wanb (eth0.3). Current score: 0

score do mwan3track deverá ser zero. Caso não seja, verifique se o tracking IP utilizado está mesmo disponível e aceita ping (icmp).


Smart Queue Management (SQM)

O OpenWrt tem um pacote chamado SQM usado para mitigar o bufferbloat: aquela latência indesejável que surge quando o roteador armazena muitos dados em buffer, e que atrapalha a sua jogatina.

A configuração é bem simples. Basta seguir as orientações deste link.

Eu usei o valor de 95% para velocidade de upload e download.


Importante

Se houver uma grande quantidade de conexões passando pelo roteador, o SQM pode aumentar o consumo de CPU (CPU Load). Exemplo:

15:34:51 up 19 min, load average: 6.17, 4.90, 4.27

Isso pode deixar os acessos a rede mais lentos. Caso seu roteador tenha um CPU mais fraco e você tenha muitos acessos atravessando o OpenWRT, observe o CPU Load com o comando “uptime”. O ideal é que o valor esteja abaixo de “2”.

15:40:30 up 25 min, load average: 0.75, 1.77, 1.96

Caso você tenha este problema, desative ou desinstale o SQM.


Unavailability Alert

You may want to set up an unavailability alert so that you know when one of your internet links goes down.

Network > MultiWAN Manager > Notify

Here you should use a bash script supported by OpenWRT. By default, alerts will be sent by e-mail. Configuration details can be viewed here.

If you have the skills, you can create scripts that send alerts via Telegram.

I send my alerts via Telegram using this simple script:

#!/bin/sh
GROUP_ID=<your_group_id>
BOT_TOKEN=<your_bot_token>
curl -s --data "text=$ACTION $INTERFACE $DEVICE" --data "chat_id=$GROUP_ID" 'https://api.telegram.org/bot'$BOT_TOKEN'/sendMessage' > /dev/null
Telegram

Telegram

The image above is an example of the alerts sent to Telegram.


I hope this article has been useful to you! 😃


Did you like the content? Check out these other interesting articles! 🔥



Support us 💖

Do you like what you find here? With every click on a banner, you help keep this site alive and free. Your support makes all the difference so that we can continue to bring you the content you love. Thank you very much! 😊


Articles you might like 📌
comments powered by Disqus