Standard library / net

net.UDPConn.WriteMsgUDPAddrPort()

Send one UDP datagram with optional ancillary data. An unconnected socket needs a destination; a connected socket uses its peer. This example uses no ancillary data. Expected stdout: '2 0 ok\n'.

Formal Syntax & Structure

go syntaxgo
func (c *UDPConn) WriteMsgUDPAddrPort(b, oob []byte, addr netip.AddrPort) (n, oobn int, err error)

Parameters & Attributes

NameTypeDescription
b[]byteByte buffer, binary representation or prefix length as indicated by its type.
oob[]byteArgument of the declared type; see example and description.
addrnetip.AddrPortAddress value or address bytes in the required representation.

Return Value

(n, oobn int, err error)

Operation result; check errors and validity indicators when returned.

Working Example

Example Snippetgo
package main
import (  "fmt"  "net"  "time")
func main() {  c := udpListener()  defer c.Close()  s := udpListener()  defer s.Close()  n, on, e := c.WriteMsgUDPAddrPort([]byte("ok"), nil, s.LocalAddr().(*net.UDPAddr).AddrPort())  check(e)  b := make([]byte, 8)  m, _, e := s.ReadFrom(b)  check(e)  fmt.Println(n, on, string(b[:m]))}func tcpListener() *net.TCPListener {  l := must(net.ListenTCP("tcp4", &net.TCPAddr{IP: net.IPv4(127, 0, 0, 1)}))  check(l.SetDeadline(time.Now().Add(3 * time.Second)))  return l}func tcpPair() (*net.TCPConn, *net.TCPConn) {  l := tcpListener()  defer l.Close()  a := must(net.DialTCP("tcp4", nil, l.Addr().(*net.TCPAddr)))  b := must(l.AcceptTCP())  check(a.SetDeadline(time.Now().Add(3 * time.Second)))  check(b.SetDeadline(time.Now().Add(3 * time.Second)))  return a, b}func udpListener() *net.UDPConn {  c := must(net.ListenUDP("udp4", &net.UDPAddr{IP: net.IPv4(127, 0, 0, 1)}))  check(c.SetDeadline(time.Now().Add(3 * time.Second)))  return c}func udpPair() (*net.UDPConn, *net.UDPConn) {  b := udpListener()  a := must(net.DialUDP("udp4", nil, b.LocalAddr().(*net.UDPAddr)))  check(a.SetDeadline(time.Now().Add(3 * time.Second)))  return a, b}
func must[T any](v T, e error) T {  if e != nil {    panic(e)  }  return v}func check(e error) {  if e != nil {    panic(e)  }}
Go Reference