Binding to an interface relies on Linux right now.

This commit is contained in:
Kyle Isom 2023-05-02 16:40:12 -07:00
parent 073dbac4bb
commit 282beeddee
2 changed files with 52 additions and 32 deletions

View File

@ -1,39 +1,18 @@
// +build: !linux
package server package server
import ( import (
"errors"
"fmt"
"net" "net"
"syscall" "runtime"
) )
func BindInterface(ip net.IP, port int, dev string) (net.PacketConn, error) { func init() {
if port == 0 { panic(fmt.Sprintf("%s is not a supported operating system", runtime.GOOS))
port = 67 }
}
func BindInterface(ip net.IP, port int, dev string) (net.PacketConn, error) {
udpAddr := &net.UDPAddr{ return nil, errors.New("server: %s does not support binding to an interface")
IP: ip,
Port: port,
}
conn, err := net.ListenUDP("udp4", udpAddr)
if err != nil {
return nil, err
}
sysconn, err := conn.SyscallConn()
if err != nil {
conn.Close()
return nil, err
}
sysconn.Control(func(fd uintptr) {
err = syscall.BindToDevice(int(fd), dev)
})
if err != nil {
conn.Close()
return nil, err
}
return conn, nil
} }

41
server/ifi_linux.go Normal file
View File

@ -0,0 +1,41 @@
// +build: linux
package server
import (
"net"
"syscall"
)
func BindInterface(ip net.IP, port int, dev string) (net.PacketConn, error) {
if port == 0 {
port = 67
}
udpAddr := &net.UDPAddr{
IP: ip,
Port: port,
}
conn, err := net.ListenUDP("udp4", udpAddr)
if err != nil {
return nil, err
}
sysconn, err := conn.SyscallConn()
if err != nil {
conn.Close()
return nil, err
}
sysconn.Control(func(fd uintptr) {
err = syscall.BindToDevice(int(fd), dev)
})
if err != nil {
conn.Close()
return nil, err
}
return conn, nil
}