vbantxt/udpconn.go

49 lines
960 B
Go
Raw Permalink Normal View History

package vbantxt
import (
"fmt"
"net"
log "github.com/sirupsen/logrus"
)
2024-11-05 18:35:39 +00:00
// udpConn represents the UDP client
type udpConn struct {
conn *net.UDPConn
}
2024-11-05 18:35:39 +00:00
// newUDPConn returns a UDP client
func newUDPConn(host string, port int) (udpConn, error) {
udpAddr, err := net.ResolveUDPAddr("udp4", fmt.Sprintf("%s:%d", host, port))
if err != nil {
2024-11-05 18:35:39 +00:00
return udpConn{}, err
}
conn, err := net.DialUDP("udp4", nil, udpAddr)
if err != nil {
2024-11-05 18:35:39 +00:00
return udpConn{}, err
}
log.Infof("Outgoing address %s", conn.RemoteAddr())
2024-11-05 18:35:39 +00:00
return udpConn{conn: conn}, nil
}
// Write implements the io.WriteCloser interface
2024-11-05 18:35:39 +00:00
func (u udpConn) Write(buf []byte) (int, error) {
n, err := u.conn.Write(buf)
if err != nil {
return 0, err
}
2024-11-05 18:35:39 +00:00
log.Debugf("Sending '%s' to: %s", string(buf), u.conn.RemoteAddr())
return n, nil
}
// Close implements the io.WriteCloser interface
2024-11-05 18:35:39 +00:00
func (u udpConn) Close() error {
err := u.conn.Close()
if err != nil {
return err
}
return nil
}