2023-05-02 23:46:04 +00:00
|
|
|
//go:build linux
|
2023-05-02 23:40:12 +00:00
|
|
|
|
|
|
|
package server
|
|
|
|
|
|
|
|
import (
|
2023-05-15 13:09:12 +00:00
|
|
|
"fmt"
|
2023-05-02 23:40:12 +00:00
|
|
|
"net"
|
|
|
|
"syscall"
|
2023-05-15 13:09:12 +00:00
|
|
|
|
|
|
|
log "git.wntrmute.dev/kyle/goutils/log"
|
2023-05-02 23:40:12 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
func BindInterface(ip net.IP, port int, dev string) (net.PacketConn, error) {
|
2023-05-15 13:09:12 +00:00
|
|
|
udpAddr, err := net.ResolveUDPAddr("udp4", fmt.Sprintf(":%d", port))
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
2023-05-02 23:40:12 +00:00
|
|
|
}
|
|
|
|
|
2023-05-15 13:09:12 +00:00
|
|
|
log.Debugf("listen on %s", udpAddr)
|
2023-05-02 23:40:12 +00:00
|
|
|
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
|
|
|
|
}
|