Disabling IPv6 on Ubuntu 19.04 when connecting to VPN

I recently noticed that when I connect to VPN from Pop_OS (based on Ubuntu 19.10), the communication continues on the regular adapter via IPv6 in addition to the VPN interface.
This is obviously not ideal, because if we’re using the VPN for privacy, this leaks our IP address and we can be traced back without any effort. The best solution would be to completely disable IPv6 address assignment at the kernel level (by editing GRUB), but I generally use it for other purposes, so I only want to disable it when I’m connected to the VPN.
To do this, let’s create a script that automatically kills IPv6:
sudo vim /etc/network/if-up.d/disableipv6
And paste this into it:
#!/bin/sh if [ "$IFACE" = "tun0" ]; then sysctl -w net.ipv6.conf.all.disable_ipv6=1 sysctl -w net.ipv6.conf.default.disable_ipv6=1 fi
If you’re not using the tun0 adapter, replace it in the script (e.g. with tap0).
Then make the script executable:
sudo chmod +x /etc/network/if-up.d/disableipv6
Once that’s done, let’s create the counterpart that re-enables IPv6 after disconnecting:
sudo vim /etc/network/if-post-down.d/enableipv6
And paste this in:
#!/bin/sh sysctl -w net.ipv6.conf.all.disable_ipv6=0 sysctl -w net.ipv6.conf.default.disable_ipv6=0
And make this one executable too:
sudo chmod +x /etc/network/if-post-down.d/enableipv6
After that, test whether there’s an IPv6 address assigned to the network interface after connecting and disconnecting using the ‘ifconfig -a’ command.