2020-10-22 00:11:49 +08:00
|
|
|
package dialer
|
|
|
|
|
|
|
|
import (
|
|
|
|
"net"
|
|
|
|
"syscall"
|
|
|
|
)
|
|
|
|
|
2020-10-25 20:31:01 +08:00
|
|
|
type controlFn = func(network, address string, c syscall.RawConn) error
|
|
|
|
|
|
|
|
func bindControl(ifaceIdx int) controlFn {
|
|
|
|
return func(network, address string, c syscall.RawConn) error {
|
|
|
|
ipStr, _, err := net.SplitHostPort(address)
|
|
|
|
if err == nil {
|
|
|
|
ip := net.ParseIP(ipStr)
|
|
|
|
if ip != nil && !ip.IsGlobalUnicast() {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
}
|
2020-10-22 00:11:49 +08:00
|
|
|
|
|
|
|
return c.Control(func(fd uintptr) {
|
|
|
|
switch network {
|
|
|
|
case "tcp4", "udp4":
|
2020-10-25 20:31:01 +08:00
|
|
|
syscall.SetsockoptInt(int(fd), syscall.IPPROTO_IP, syscall.IP_BOUND_IF, ifaceIdx)
|
2020-10-22 00:11:49 +08:00
|
|
|
case "tcp6", "udp6":
|
2020-10-25 20:31:01 +08:00
|
|
|
syscall.SetsockoptInt(int(fd), syscall.IPPROTO_IPV6, syscall.IPV6_BOUND_IF, ifaceIdx)
|
2020-10-22 00:11:49 +08:00
|
|
|
}
|
|
|
|
})
|
|
|
|
}
|
2020-10-25 20:31:01 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
func bindIfaceToDialer(dialer *net.Dialer, ifaceName string) error {
|
|
|
|
iface, err := net.InterfaceByName(ifaceName)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
dialer.Control = bindControl(iface.Index)
|
2020-10-22 00:11:49 +08:00
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func bindIfaceToListenConfig(lc *net.ListenConfig, ifaceName string) error {
|
|
|
|
iface, err := net.InterfaceByName(ifaceName)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2020-10-25 20:31:01 +08:00
|
|
|
lc.Control = bindControl(iface.Index)
|
2020-10-22 00:11:49 +08:00
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|