Now and then you need to get a second machine online through your laptop — a headless box on a bench, a server with no working uplink yet, a device on a little isolated LAN. You don't need a fancy connection-sharing GUI; on Linux it's two firewall rules and a sysctl. Here's the lot, plus the one gotcha that catches people out.
The setup
Say your laptop has internet on wlp... (wifi) and the other box is reachable on a wired interface where your laptop is 192.168.50.50 and the box is 192.168.50.2.
Enable forwarding and NAT the box's subnet out through your wifi:
sudo sysctl -w net.ipv4.ip_forward=1
sudo iptables -t nat -A POSTROUTING -s 192.168.50.0/24 -o wlp... -j MASQUERADE
sudo iptables -I FORWARD 1 -s 192.168.50.0/24 -o wlp... -j ACCEPT
sudo iptables -I FORWARD 1 -d 192.168.50.0/24 -i wlp... -m state --state RELATED,ESTABLISHED -j ACCEPT
Then on the other box, point its default route at your laptop:
ip route replace default via 192.168.50.50 dev <its-iface>
That's it — the box now reaches the internet, NATed behind your laptop's wifi address. Set its DNS to something sensible (1.1.1.1 will do) if it doesn't have one.
The gotcha: captive portals authorise you
Here's the bit worth knowing. If your laptop's wifi is behind a captive portal or an enterprise login (eduroam, a guest portal, a hotel), the upstream only knows your laptop. The other box's traffic is NATed, so it appears to the network as your laptop — which means it rides your already-authenticated session and works. Conversely, if your laptop isn't through the portal yet, sharing won't magically get the other box online either. The shared box inherits your laptop's auth state, for better or worse. (This is genuinely handy: it's how you give internet to a device that could never click through a portal itself.)
Tidy up after yourself
These are runtime-only and vanish on reboot, but remove them when you're done — and leave ip_forward alone if you run containers (Docker/Podman/Incus/libvirt all need it; don't set it back to 0 reflexively):
sudo iptables -t nat -D POSTROUTING -s 192.168.50.0/24 -o wlp... -j MASQUERADE
sudo iptables -D FORWARD -s 192.168.50.0/24 -o wlp... -j ACCEPT
sudo iptables -D FORWARD -d 192.168.50.0/24 -i wlp... -m state --state RELATED,ESTABLISHED -j ACCEPT
Two lines of NAT and you've turned your laptop into a router. I hope you find this helpful!
No comments:
Post a Comment