Skip to content

Use all your internet connections at once on Windows, macOS, Linux and Android: per-connection load balancing over Wi-Fi, Ethernet, mobile data and phone tethers

Pick a free address for the adapter; show netsh's reason in errors (#43) (#44)

Rohit Mahtofc2eb32f5b76
diff --git a/CHANGELOG.md b/CHANGELOG.md
index a98b974..893a8c3 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -11,6 +11,15 @@ entry here before pushing a version tag.
then every 6 hours, and turns into *Update to v0.3.4* when there is one; click it to open the release
page.
+### Fixed
+- **net-merge no longer fails to turn on when another app already uses its address** (#43). The
+ adapter used to always take `198.18.0.1`, which VPN and proxy apps such as Clash, sing-box and v2rayN
+ often use as well. It now picks a free range at start.
+- **Turning on is more reliable on Windows.** net-merge now waits for its adapter to appear before giving
+ it an address, and tries again if the first attempt fails.
+- **Errors in the tray now show the reason.** The menu has room for only the start of an error, and that
+ used to be taken up by the command that failed, so the reason never showed (#43).
+
## [0.3.3] - 2026-10-20
### Added
diff --git a/internal/tun/tun.go b/internal/tun/tun.go
index d858fc6..24dea1a 100644
--- a/internal/tun/tun.go
+++ b/internal/tun/tun.go
@@ -6,6 +6,8 @@ import (
"context"
"fmt"
"net"
+ "net/netip"
+ "strings"
"sync"
"time"
@@ -21,12 +23,11 @@ import (
"github.com/xjasonlyu/tun2socks/v2/tunnel"
"net-merge/internal/engine"
+ "net-merge/internal/logx"
)
const (
tunName = "net-merge"
- tunIP = "198.18.0.1"
- tunMask = "255.255.255.0"
// A ULA on purpose. The OS's source-address policy (RFC 6724, on Windows and in glibc) prefers
// IPv4 over IPv6 when the only IPv6 source on the route is a ULA, so dual-stack sites go over
// IPv4 and spread across every adapter, while IPv6-only sites (and explicit IPv6) still work
@@ -36,6 +37,73 @@ const (
tunIP6 = "fd6e:6d65:7267::1"
)
+// tunRange is where the adapter's IPv4 subnet comes from. 198.18.0.0/15 is reserved for benchmarks
+// (RFC 2544), so no real network uses it, but other TUN apps (Clash, sing-box, v2rayN) like it too,
+// and Windows refuses an address another adapter already has (#43). So On picks a free /24 in it.
+var tunRange = netip.MustParsePrefix("198.18.0.0/15")
+
+// pickNet returns the adapter's address and subnet: .1 of the first /24 in tunRange that overlaps none
+// of used, or else of the first whose .1 nobody holds (sitting inside another app's bigger subnet
+// works, a duplicate address does not).
+func pickNet(used []netip.Prefix) netip.Prefix {
+ var spare netip.Prefix
+ for i := range 1 << (24 - tunRange.Bits()) {
+ b := tunRange.Addr().As4()
+ b[1] += byte(i >> 8)
+ b[2], b[3] = byte(i), 1
+ p := netip.PrefixFrom(netip.AddrFrom4(b), 24)
+ free, held := true, false
+ for _, u := range used {
+ free = free && !p.Overlaps(u)
+ held = held || u.Addr() == p.Addr()
+ }
+ if free {
+ return p
+ }
+ if !held && !spare.IsValid() {
+ spare = p
+ }
+ }
+ if spare.IsValid() {
+ return spare
+ }
+ return netip.PrefixFrom(tunRange.Addr().Next(), 24)
+}
+
+// usedNets lists the IPv4 subnets of every adapter except ours (skip).
+func usedNets(skip string) []netip.Prefix {
+ ifs, _ := net.Interfaces()
+ var out []netip.Prefix
+ for _, ifc := range ifs {
+ if ifc.Name == skip {
+ continue
+ }
+ addrs, _ := ifc.Addrs()
+ for _, a := range addrs {
+ n, ok := a.(*net.IPNet)
+ if !ok || n.IP.To4() == nil {
+ continue
+ }
+ ones, bits := n.Mask.Size()
+ if bits == 128 {
+ ones -= 96
+ }
+ out = append(out, netip.PrefixFrom(netip.AddrFrom4([4]byte(n.IP.To4())), ones))
+ }
+ }
+ return out
+}
+
+// cmdError puts the tool's own message first. The tray shows only an error's first 70 characters,
+// and with the command line first that was all command and no reason (#43).
+func cmdError(name string, args []string, err error, out []byte) error {
+ cmdline := name + " " + strings.Join(args, " ")
+ if msg := strings.Join(strings.Fields(string(out)), " "); msg != "" {
+ return fmt.Errorf("%s (%s: %v)", msg, cmdline, err)
+ }
+ return fmt.Errorf("%s: %v", cmdline, err)
+}
+
// openName is what the OS is asked to call the adapter; macOS only accepts "utunN" and picks the number.
var openName = tunName
@@ -159,7 +227,11 @@ func (t *Tun) On() (err error) {
}()
tunnel.T().SetProxy(tunProxy{t.B})
- if t.idx, err = configure(t.dev.Name(), t.MTU); err != nil {
+ ip4 := pickNet(usedNets(t.dev.Name()))
+ if ip4.Addr() != tunRange.Addr().Next() {
+ logx.Printf("note: another adapter is on %s, using %s\n", netip.PrefixFrom(tunRange.Addr(), 24), ip4)
+ }
+ if t.idx, err = configure(t.dev.Name(), t.MTU, ip4); err != nil {
return err
}
t.on = true
diff --git a/internal/tun/tun_darwin.go b/internal/tun/tun_darwin.go
index 341d742..866755a 100644
--- a/internal/tun/tun_darwin.go
+++ b/internal/tun/tun_darwin.go
@@ -3,6 +3,7 @@ package tun
import (
"fmt"
"net"
+ "net/netip"
"os/exec"
"regexp"
"strings"
@@ -24,7 +25,7 @@ func init() {
// configure gives the new utun its addresses and capture routes, and returns its index.
// ponytail: shells out to ifconfig/route (once per on/off); PF_ROUTE messages if that ever matters.
-func configure(name string, _ int) (int, error) {
+func configure(name string, _ int, ip4 netip.Prefix) (int, error) {
ifc, err := net.InterfaceByName(name)
if err != nil {
return 0, fmt.Errorf("adapter %q did not appear: %w", name, err)
@@ -33,7 +34,8 @@ func configure(name string, _ int) (int, error) {
if err := startScopedSync(); err != nil {
return ifc.Index, err
}
- if err := run("/sbin/ifconfig", name, "inet", tunIP, tunIP, "up"); err != nil {
+ addr := ip4.Addr().String()
+ if err := run("/sbin/ifconfig", name, "inet", addr, addr, "up"); err != nil {
return ifc.Index, err
}
for _, dst := range routes4 {
@@ -73,7 +75,7 @@ func delRoutes(idx int) {
func run(name string, args ...string) error {
out, err := exec.Command(name, args...).CombinedOutput()
if err != nil {
- return fmt.Errorf("%s %s: %w: %s", name, strings.Join(args, " "), err, strings.TrimSpace(string(out)))
+ return cmdError(name, args, err, out)
}
return nil
}
diff --git a/internal/tun/tun_linux.go b/internal/tun/tun_linux.go
index 9dbe412..0957b75 100644
--- a/internal/tun/tun_linux.go
+++ b/internal/tun/tun_linux.go
@@ -3,6 +3,7 @@ package tun
import (
"fmt"
"net"
+ "net/netip"
"github.com/vishvananda/netlink"
"golang.org/x/sys/unix"
@@ -15,13 +16,13 @@ const openHint = "needs root or CAP_NET_ADMIN, and /dev/net/tun"
// configure gives the new adapter its addresses and routes, and returns its index. tun2socks has
// already set the MTU. Everything goes through netlink rather than `ip`, so it also works when the
// privilege is a file capability, which child processes don't inherit.
-func configure(name string, _ int) (int, error) {
+func configure(name string, _ int, ip4 netip.Prefix) (int, error) {
link, err := netlink.LinkByName(name)
if err != nil {
return 0, fmt.Errorf("adapter %q did not appear: %w", name, err)
}
idx := link.Attrs().Index
- if err := netlink.AddrReplace(link, &netlink.Addr{IPNet: hostCIDR(tunIP + "/24")}); err != nil {
+ if err := netlink.AddrReplace(link, &netlink.Addr{IPNet: hostCIDR(ip4.String())}); err != nil {
return idx, fmt.Errorf("set address: %w", err)
}
if err := netlink.LinkSetUp(link); err != nil {
diff --git a/internal/tun/tun_test.go b/internal/tun/tun_test.go
new file mode 100644
index 0000000..e3c637b
--- /dev/null
+++ b/internal/tun/tun_test.go
@@ -0,0 +1,55 @@
+package tun
+
+import (
+ "errors"
+ "net"
+ "net/netip"
+ "strings"
+ "testing"
+)
+
+func TestPickNetSkipsAdaptersOnTheRange(t *testing.T) {
+ p := func(s string) netip.Prefix { return netip.MustParsePrefix(s) }
+ for _, c := range []struct {
+ name string
+ used []netip.Prefix
+ want string
+ }{
+ {"nothing else there", nil, "198.18.0.1/24"},
+ {"real LANs only", []netip.Prefix{p("192.168.1.12/24"), p("10.0.0.5/8"), p("127.0.0.1/8")}, "198.18.0.1/24"},
+ {"Clash Meta on a /30", []netip.Prefix{p("198.18.0.1/30")}, "198.18.1.1/24"},
+ {"another app on a /16", []netip.Prefix{p("198.18.0.1/16")}, "198.19.0.1/24"},
+ {"two /24s taken", []netip.Prefix{p("198.18.0.7/24"), p("198.18.1.1/24")}, "198.18.2.1/24"},
+ // The whole range is someone's subnet: sit inside it, but never on the address it holds.
+ {"whole /15 taken", []netip.Prefix{p("198.18.0.1/15")}, "198.18.1.1/24"},
+ } {
+ if got := pickNet(c.used); got.String() != c.want {
+ t.Errorf("%s: pickNet = %s, want %s", c.name, got, c.want)
+ }
+ }
+}
+
+func TestUsedNetsReadsSubnets(t *testing.T) {
+ if ifs, _ := net.Interfaces(); len(ifs) == 0 {
+ t.Skip("the OS lists no adapters (qemu-user on s390x can't translate netlink)")
+ }
+ used := usedNets("")
+ for _, u := range used {
+ if u.String() == "127.0.0.1/8" {
+ return
+ }
+ }
+ t.Errorf("loopback 127.0.0.1/8 not among %v", used)
+}
+
+func TestCmdErrorPutsTheReasonFirst(t *testing.T) {
+ err := cmdError("netsh", strings.Fields("interface ipv4 set address name=13 source=static address=198.18.0.1"),
+ errors.New("exit status 1"), []byte("\r\nThe object already exists.\r\n\r\n"))
+ want := "The object already exists. (netsh interface ipv4 set address name=13 source=static address=198.18.0.1: exit status 1)"
+ if err.Error() != want {
+ t.Errorf("got %q\nwant %q", err, want)
+ }
+ if err := cmdError("route", []string{"add"}, errors.New("exit status 1"), nil); err.Error() != "route add: exit status 1" {
+ t.Errorf("no output: got %q", err)
+ }
+}
diff --git a/internal/tun/tun_windows.go b/internal/tun/tun_windows.go
index 965f92b..fb68744 100644
--- a/internal/tun/tun_windows.go
+++ b/internal/tun/tun_windows.go
@@ -3,6 +3,7 @@ package tun
import (
"fmt"
"net"
+ "net/netip"
"os"
"os/exec"
"path/filepath"
@@ -34,24 +35,30 @@ func init() {
}
// configure gives the new adapter its addresses, MTU and routes, and returns its index.
-func configure(name string, mtu int) (int, error) {
- if err := run("netsh", "interface", "ipv4", "set", "address", "name="+name, "source=static",
- "address="+tunIP, "mask="+tunMask, "store=active"); err != nil {
- return 0, err
- }
+func configure(name string, mtu int, ip4 netip.Prefix) (int, error) {
ifc, err := waitIface(name, 5*time.Second)
if err != nil {
return 0, err
}
- // Windows now and then drops an address set the moment the adapter appears, and without it
- // nothing routed into the adapter can be sent (all traffic dies), so make sure it stuck.
- for try := 1; !hasAddr(ifc, tunIP); try++ {
+ idx := strconv.Itoa(ifc.Index)
+ addr, mask := ip4.Addr().String(), net.IP(net.CIDRMask(ip4.Bits(), 32)).String()
+ // By index: netsh can know the adapter a moment before it knows its name.
+ setAddr := func() error {
+ return run("netsh", "interface", "ipv4", "set", "address", "name="+idx, "source=static",
+ "address="+addr, "mask="+mask, "store=active")
+ }
+ err = setAddr()
+ // Windows now and then refuses or drops an address set the moment the adapter appears, and
+ // without it nothing routed into the adapter can be sent (all traffic dies), so make sure it stuck.
+ for try := 1; !hasAddr(ifc, addr); try++ {
if try > 20 {
- return ifc.Index, fmt.Errorf("adapter %q did not keep its address %s", name, tunIP)
+ if err == nil {
+ err = fmt.Errorf("adapter %q did not keep its address %s", name, addr)
+ }
+ return ifc.Index, err
}
if try%4 == 0 {
- run("netsh", "interface", "ipv4", "set", "address", "name="+name, "source=static",
- "address="+tunIP, "mask="+tunMask, "store=active")
+ err = setAddr()
}
time.Sleep(250 * time.Millisecond)
}
@@ -59,7 +66,6 @@ func configure(name string, mtu int) (int, error) {
startStrongHost(ifc.Index)
// Windows gives Wintun adapters an MTU of 65535. Match the stack's MTU, so Windows sizes TCP
// segments to it and fragments bigger UDP datagrams instead of sending packets the stack drops.
- idx := strconv.Itoa(ifc.Index)
mtuArg := "mtu=" + strconv.Itoa(mtu)
if e := run("netsh", "interface", "ipv4", "set", "subinterface", "interface="+idx, mtuArg, "store=active"); e != nil {
logx.Printf("warning: could not set IPv4 MTU: %v\n", e)
@@ -100,7 +106,7 @@ func run(name string, args ...string) error {
cmd.SysProcAttr = &syscall.SysProcAttr{HideWindow: true}
out, err := cmd.CombinedOutput()
if err != nil {
- return fmt.Errorf("%s %s: %v: %s", name, strings.Join(args, " "), err, strings.TrimSpace(string(out)))
+ return cmdError(name, args, err, out)
}
return nil
}
diff --git a/scripts/linux-e2e.sh b/scripts/linux-e2e.sh
index 0100b2c..f1b2315 100755
--- a/scripts/linux-e2e.sh
+++ b/scripts/linux-e2e.sh
@@ -31,6 +31,7 @@ cleanup() {
sudo ip netns del nmup 2>/dev/null
sudo ip link del nmup-h 2>/dev/null
sudo ip link del nmgw-h 2>/dev/null
+ sudo ip link del nmclash 2>/dev/null
sudo ip rule del iif nmgw-h lookup 100 2>/dev/null
sudo ip route flush table 100 2>/dev/null
sudo iptables -t nat -D POSTROUTING -s 10.88.0.0/24 -o "$REAL" -j MASQUERADE 2>/dev/null
@@ -89,6 +90,9 @@ ip=$(curl -4 -s --max-time 10 --interface nmup-h https://api.ipify.org) &&
echo "== adapter detection (the veth is virtual, so it is used only via -include)"
"$BIN" list
+# Another TUN app (Clash, sing-box) on net-merge's default address: it must pick another range (#43).
+sudo ip link add nmclash type dummy && sudo ip addr add 198.18.0.1/30 dev nmclash && sudo ip link set nmclash up
+
if command -v dig >/dev/null; then
echo "== DNS over UDP without net-merge (baseline): 1.1.1.1 $(dns_answers 1.1.1.1)/12, 8.8.8.8 $(dns_answers 8.8.8.8)/12, 9.9.9.9 $(dns_answers 9.9.9.9)/12"
fi
@@ -103,6 +107,9 @@ grep -q '0.0.0.0/1' <<<"$routes" && grep -q '128.0.0.0/1' <<<"$routes" &&
pass "capture routes 0.0.0.0/1 + 128.0.0.0/1 on net-merge" || fail "capture routes missing: $routes"
mtu=$(cat /sys/class/net/net-merge/mtu)
[ "$mtu" = 9000 ] && pass "TUN MTU is 9000" || fail "TUN MTU is $mtu, want 9000"
+addr=$(ip -4 -o addr show dev net-merge | awk '{print $4}')
+[ "$addr" = 198.18.1.1/24 ] && pass "TUN moved to 198.18.1.1/24, off the other app's 198.18.0.1/30" ||
+ fail "TUN address is $addr, want 198.18.1.1/24"
code=$(curl -4 -s --max-time 10 -o /dev/null -w '%{http_code}' https://example.com)
[ "$code" = 200 ] && pass "plain HTTPS works through net-merge" || fail "HTTPS through net-merge: $code"
diff --git a/scripts/macos-smoke.sh b/scripts/macos-smoke.sh
index 95959cf..24746e3 100755
--- a/scripts/macos-smoke.sh
+++ b/scripts/macos-smoke.sh
@@ -36,8 +36,8 @@ sleep 4 # let the internet probes finish
"$BIN" status -state-dir "$STATE"
[ "$(captured)" = 2 ] && pass "capture routes 0/1 + 128.0/1 present" || fail "capture routes: $(captured), want 2"
-tun=$(ifconfig -l | tr ' ' '\n' | grep '^utun' | while read -r i; do ifconfig "$i" | grep -q 'inet 198.18.0.1' && echo "$i"; done)
-[ -n "$tun" ] && pass "utun $tun has 198.18.0.1" || fail "no utun with 198.18.0.1"
+tun=$(ifconfig -l | tr ' ' '\n' | grep '^utun' | while read -r i; do ifconfig "$i" | grep -qE 'inet 198\.1[89]\.[0-9]+\.1 ' && echo "$i"; done)
+[ -n "$tun" ] && pass "utun $tun has an address in 198.18.0.0/15" || fail "no utun with an address in 198.18.0.0/15"
mtu=$(ifconfig "$tun" 2>/dev/null | sed -n 's/.*mtu \([0-9]*\).*/\1/p')
[ "$mtu" = 9000 ] && pass "TUN MTU is 9000" || fail "TUN MTU is $mtu, want 9000"
[ "$(http)" = 200 ] && pass "HTTPS works through net-merge" || fail "HTTPS through net-merge failed"