📖 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
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.
There are 3 ways to achieve this.
Click to see more.
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.
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.
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!
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.
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.
Each ISP router will need to be connected to a WAN port, which represents the internet links.
10.128.25.1
255.255.255.0
10.128.25.254
Disabled
10.128.20.1
255.255.255.0
10.128.20.254
Disabled
The local network will be the LAN, where the DHCP service will work and where we will administer OpenWRT.
10.128.15.1
Enabled
Disabled
Disabled
Disabled
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.
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.
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
[2] LAN IP
Network > Interfaces > LAN
[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.
Neste exemplo, o DHCP entregará IPs na faixa entre 10.128.15.100
-10.128.15.150
.
[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.
[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.
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.
[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”.
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.
[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.
wan
Protocol
: Static addressDevice
: eth0.2IP
: 10.128.25.1Netmask
: 255.255.255.0Gateway
: 10.128.25.254Use 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 interfacewanb
Protocol
: Static addressDevice
: eth0.3IP
: 10.128.20.1Netmask
: 255.255.255.0Gateway
: 10.128.20.254Use 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
Device
: eth0.3Request IPv6-address
: tryUse default gateway
: marcadoUse DNS servers advertised by peer
: marcadoUse gateway metric
: 40IPv6 source routing
: desativadoDelegate IPv6 prefixes
: marcadoIPv6 assignment length
: desativadoFirewall 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á.
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/
Esta seção aborda problemas comuns.
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
Depois remova as interfaces WANB e WANB6 e reconfigure as mesmas.
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).
[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.
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:
Caso queira, você pode utilizar outros IPs para fazer os testes de disponibilidade dos ISP.
[2] Verificar o status do MultiWAN
Status > MultiWAN Manager
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.
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:
Exemplo alternativo de rastreamento de disponibilidade dos links internet:
Para informação, estes são os IPv4 padrão usados no rastreio.
É 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.
Será que fica bom usar 2 links de internet ao mesmo tempo? Eu diria que fica interessante!
Podemos observar que cada link de internet tem um consumo diferente de banda.
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!
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
O score do mwan3track deverá ser zero. Caso não seja, verifique se o tracking IP utilizado está mesmo disponível e aceita ping (icmp).
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.
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.
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
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! 🔥
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! 😊