42 lines
669 B
Go
42 lines
669 B
Go
//go:build linux
|
|
|
|
package server
|
|
|
|
import (
|
|
"fmt"
|
|
"net"
|
|
"syscall"
|
|
|
|
log "git.wntrmute.dev/kyle/goutils/log"
|
|
)
|
|
|
|
func BindInterface(ip net.IP, port int, dev string) (net.PacketConn, error) {
|
|
udpAddr, err := net.ResolveUDPAddr("udp4", fmt.Sprintf(":%d", port))
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
log.Debugf("listen on %s", udpAddr)
|
|
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
|
|
}
|