Standard library / net

net.ListenConfig.ListenPacket()

Bind a local datagram socket; close after use. Expected stdout: 'udp\n'.

Formal Syntax & Structure

go syntaxgo
func (lc *ListenConfig) ListenPacket(ctx context.Context, network, address string) (PacketConn, error)

Parameters & Attributes

NameTypeDescription
ctxcontext.ContextContext controlling cancellation.
networkstringNetwork family such as tcp4 or udp4.
addressstringNetwork address including port when required.

Return Value

(PacketConn, error)

Operation result; check errors and validity indicators when returned.

Working Example

Example Snippetgo
package main
import (  "context"  "fmt"  "net")
func main() {  c := must((&net.ListenConfig{}).ListenPacket(context.Background(), "udp4", "127.0.0.1:0"))  defer c.Close()  fmt.Println(c.LocalAddr().Network())}
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