Skip to content

Commit 19d9e29

Browse files
committed
feat: fetch flags and mtu from if_msghdr directly
Signed-off-by: ruokeqx <[email protected]>
1 parent 12269c2 commit 19d9e29

File tree

1 file changed

+10
-25
lines changed

1 file changed

+10
-25
lines changed

tun/tun_darwin.go

Lines changed: 10 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -6,14 +6,12 @@
66
package tun
77

88
import (
9-
"errors"
109
"fmt"
1110
"io"
1211
"net"
1312
"os"
1413
"sync"
1514
"syscall"
16-
"time"
1715
"unsafe"
1816

1917
"golang.org/x/sys/unix"
@@ -30,18 +28,6 @@ type NativeTun struct {
3028
closeOnce sync.Once
3129
}
3230

33-
func retryInterfaceByIndex(index int) (iface *net.Interface, err error) {
34-
for i := 0; i < 20; i++ {
35-
iface, err = net.InterfaceByIndex(index)
36-
if err != nil && errors.Is(err, unix.ENOMEM) {
37-
time.Sleep(time.Duration(i) * time.Second / 3)
38-
continue
39-
}
40-
return iface, err
41-
}
42-
return nil, err
43-
}
44-
4531
func (tun *NativeTun) routineRouteListener(tunIfindex int) {
4632
var (
4733
statusUp bool
@@ -62,26 +48,23 @@ func (tun *NativeTun) routineRouteListener(tunIfindex int) {
6248
return
6349
}
6450

65-
if n < 14 {
51+
//sizeof(if_msghdr) = 112
52+
if n < 112 {
6653
continue
6754
}
6855

69-
if data[3 /* type */] != unix.RTM_IFINFO {
56+
if data[3 /* ifm_type */] != unix.RTM_IFINFO {
7057
continue
7158
}
72-
ifindex := int(*(*uint16)(unsafe.Pointer(&data[12 /* ifindex */])))
59+
ifindex := int(*(*uint16)(unsafe.Pointer(&data[12 /* ifm_index */])))
7360
if ifindex != tunIfindex {
7461
continue
7562
}
7663

77-
iface, err := retryInterfaceByIndex(ifindex)
78-
if err != nil {
79-
tun.errors <- err
80-
return
81-
}
64+
flags := int(*(*uint32)(unsafe.Pointer(&data[8 /* ifm_flags */])))
8265

8366
// Up / Down event
84-
up := (iface.Flags & net.FlagUp) != 0
67+
up := (flags & syscall.IFF_UP) != 0
8568
if up != statusUp && up {
8669
tun.events <- EventUp
8770
}
@@ -90,11 +73,13 @@ func (tun *NativeTun) routineRouteListener(tunIfindex int) {
9073
}
9174
statusUp = up
9275

76+
mtu := int(*(*uint32)(unsafe.Pointer(&data[24 /* ifm_data.ifi_mtu */])))
77+
9378
// MTU changes
94-
if iface.MTU != statusMTU {
79+
if mtu != statusMTU {
9580
tun.events <- EventMTUUpdate
9681
}
97-
statusMTU = iface.MTU
82+
statusMTU = mtu
9883
}
9984
}
10085

0 commit comments

Comments
 (0)