Fix SO_BINDTOIFINDEX usage

This commit is contained in:
世界 2024-02-29 12:53:56 +08:00
parent 8e89f9b4dc
commit 6e3921083b
No known key found for this signature in database
GPG key ID: CD109927C34A63C4

View file

@ -14,19 +14,18 @@ var ifIndexDisabled atomic.Bool
func bindToInterface(conn syscall.RawConn, network string, address string, finder InterfaceFinder, interfaceName string, interfaceIndex int, preferInterfaceName bool) error { func bindToInterface(conn syscall.RawConn, network string, address string, finder InterfaceFinder, interfaceName string, interfaceIndex int, preferInterfaceName bool) error {
return Raw(conn, func(fd uintptr) error { return Raw(conn, func(fd uintptr) error {
if interfaceIndex != -1 { if !preferInterfaceName && !ifIndexDisabled.Load() {
return unix.SetsockoptInt(int(fd), unix.SOL_SOCKET, unix.SO_BINDTOIFINDEX, interfaceIndex) if interfaceIndex == -1 {
} if interfaceName == "" {
if interfaceName == "" { return os.ErrInvalid
return os.ErrInvalid }
} var err error
if !preferInterfaceName && finder != nil && !ifIndexDisabled.Load() { interfaceIndex, err = finder.InterfaceIndexByName(interfaceName)
var err error if err != nil {
interfaceIndex, err = finder.InterfaceIndexByName(interfaceName) return err
if err != nil { }
return err
} }
err = unix.SetsockoptInt(int(fd), unix.SOL_SOCKET, unix.SO_BINDTOIFINDEX, interfaceIndex) err := unix.SetsockoptInt(int(fd), unix.SOL_SOCKET, unix.SO_BINDTOIFINDEX, interfaceIndex)
if err == nil { if err == nil {
return nil return nil
} else if E.IsMulti(err, unix.ENOPROTOOPT, unix.EINVAL) { } else if E.IsMulti(err, unix.ENOPROTOOPT, unix.EINVAL) {
@ -35,6 +34,9 @@ func bindToInterface(conn syscall.RawConn, network string, address string, finde
return err return err
} }
} }
if interfaceName == "" {
return os.ErrInvalid
}
return unix.BindToDevice(int(fd), interfaceName) return unix.BindToDevice(int(fd), interfaceName)
}) })
} }