wireguard-go/src/conn.go

63 lines
943 B
Go
Raw Normal View History

package main
import (
"net"
)
func updateUDPConn(device *Device) error {
netc := &device.net
netc.mutex.Lock()
2017-08-17 12:58:18 +02:00
defer netc.mutex.Unlock()
// close existing connection
if netc.conn != nil {
netc.conn.Close()
2017-08-22 17:22:45 +02:00
netc.conn = nil
}
// open new connection
if device.tun.isUp.Get() {
2017-08-17 12:58:18 +02:00
// listen on new address
conn, err := net.ListenUDP("udp", netc.addr)
2017-08-17 12:58:18 +02:00
if err != nil {
return err
}
2017-08-17 12:58:18 +02:00
2017-08-22 17:22:45 +02:00
// set fwmark
err = setMark(netc.conn, netc.fwmark)
if err != nil {
return err
}
2017-08-17 12:58:18 +02:00
// retrieve port (may have been chosen by kernel)
addr := conn.LocalAddr()
netc.conn = conn
2017-08-22 17:22:45 +02:00
netc.addr, _ = net.ResolveUDPAddr(
addr.Network(),
addr.String(),
)
// notify goroutines
2017-08-17 12:58:18 +02:00
signalSend(device.signal.newUDPConn)
}
2017-08-17 12:58:18 +02:00
return nil
}
func closeUDPConn(device *Device) {
netc := &device.net
netc.mutex.Lock()
if netc.conn != nil {
netc.conn.Close()
}
netc.mutex.Unlock()
signalSend(device.signal.newUDPConn)
}