Add net control funcs

This commit is contained in:
世界 2022-06-30 17:39:41 +08:00
parent a784aec420
commit ddfe73e899
No known key found for this signature in database
GPG key ID: CD109927C34A63C4
7 changed files with 97 additions and 0 deletions

View file

@ -0,0 +1,17 @@
package control
import (
"syscall"
"github.com/sagernet/sing/common"
)
func BindToInterface(interfaceName string) Func {
return func(network, address string, conn syscall.RawConn) error {
var innerErr error
err := conn.Control(func(fd uintptr) {
innerErr = syscall.BindToDevice(int(fd), interfaceName)
})
return common.AnyError(innerErr, err)
}
}

View file

@ -0,0 +1,7 @@
//go:build !linux
package control
func BindToInterface(interfaceName string) Func {
return nil
}

View file

@ -0,0 +1,21 @@
package control
import (
"syscall"
)
type Func = func(network, address string, conn syscall.RawConn) error
func Append(oldFunc Func, newFunc Func) Func {
if oldFunc == nil {
return newFunc
} else if newFunc == nil {
return oldFunc
}
return func(network, address string, conn syscall.RawConn) error {
if err := oldFunc(network, address, conn); err != nil {
return err
}
return newFunc(network, address, conn)
}
}

View file

@ -0,0 +1,17 @@
package control
import (
"syscall"
"github.com/sagernet/sing/common"
)
func RoutingMark(mark int) Func {
return func(network, address string, conn syscall.RawConn) error {
var innerErr error
err := conn.Control(func(fd uintptr) {
innerErr = syscall.SetsockoptInt(int(fd), syscall.SOL_SOCKET, syscall.SO_MARK, mark)
})
return common.AnyError(innerErr, err)
}
}

View file

@ -0,0 +1,7 @@
//go:build !linux
package control
func RoutingMark(mark int) Func {
return nil
}

View file

@ -0,0 +1,21 @@
package control
import (
"syscall"
"github.com/sagernet/sing/common"
)
func ReuseAddr() Func {
return func(network, address string, conn syscall.RawConn) error {
var innerErr error
err := conn.Control(func(fd uintptr) {
const SO_REUSEPORT = 0xf
innerErr = common.AnyError(
syscall.SetsockoptInt(int(fd), syscall.SOL_SOCKET, syscall.SO_REUSEADDR, 1),
syscall.SetsockoptInt(int(fd), syscall.SOL_SOCKET, SO_REUSEPORT, 1),
)
})
return common.AnyError(innerErr, err)
}
}

View file

@ -0,0 +1,7 @@
//go:build !linux
package control
func ReuseAddr() Func {
return nil
}