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 {
return Raw(conn, func(fd uintptr) error {
if interfaceIndex != -1 {
return unix.SetsockoptInt(int(fd), unix.SOL_SOCKET, unix.SO_BINDTOIFINDEX, interfaceIndex)
}
if interfaceName == "" {
return os.ErrInvalid
}
if !preferInterfaceName && finder != nil && !ifIndexDisabled.Load() {
var err error
interfaceIndex, err = finder.InterfaceIndexByName(interfaceName)
if err != nil {
return err
if !preferInterfaceName && !ifIndexDisabled.Load() {
if interfaceIndex == -1 {
if interfaceName == "" {
return os.ErrInvalid
}
var err error
interfaceIndex, err = finder.InterfaceIndexByName(interfaceName)
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 {
return nil
} 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
}
}
if interfaceName == "" {
return os.ErrInvalid
}
return unix.BindToDevice(int(fd), interfaceName)
})
}