Standard library / net

net.UnixConn.ReadMsgUnix()

Read payload and ancillary data, returning separate byte counts, flags and a Unix source address. This example sends payload only and checks that the truncation flag is clear; other flags can be set. Expected stdout: 'true\n'.

Formal Syntax & Structure

go syntaxgo
func (c *UnixConn) ReadMsgUnix(b, oob []byte) (n, oobn, flags int, addr *UnixAddr, 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.

Return Value

(n, oobn, flags int, addr *UnixAddr, err error)

Operation result; check errors and validity indicators when returned.

Working Example

Example Snippetgo
package main
import (  "fmt"  "net"  "os"  "path/filepath"  "syscall"  "time")
func main() {  a, b, done := unixPackets()  defer done()  must(a.WriteToUnix([]byte("hi"), b.LocalAddr().(*net.UnixAddr)))  buf := make([]byte, 8)  n, oobn, flags, from, e := b.ReadMsgUnix(buf, nil)  check(e)  fmt.Println(string(buf[:n]) == "hi" && oobn == 0 && flags&syscall.MSG_TRUNC == 0 && from.Name == a.LocalAddr().String())}func unixDir() (string, func()) {  d := must(os.MkdirTemp("", "bm-unix-"))  return d, func() { check(os.RemoveAll(d)) }}func unixListener() (*net.UnixListener, func()) {  d, clean := unixDir()  l := must(net.ListenUnix("unix", &net.UnixAddr{Name: filepath.Join(d, "s"), Net: "unix"}))  check(l.SetDeadline(time.Now().Add(3 * time.Second)))  return l, func() { l.Close(); clean() }}func unixPair() (*net.UnixConn, *net.UnixConn, func()) {  l, clean := unixListener()  c := must(net.DialUnix("unix", nil, l.Addr().(*net.UnixAddr)))  s := must(l.AcceptUnix())  check(c.SetDeadline(time.Now().Add(3 * time.Second)))  check(s.SetDeadline(time.Now().Add(3 * time.Second)))  return c, s, func() { c.Close(); s.Close(); clean() }}func unixPackets() (*net.UnixConn, *net.UnixConn, func()) {  d, clean := unixDir()  a := must(net.ListenUnixgram("unixgram", &net.UnixAddr{Name: filepath.Join(d, "a"), Net: "unixgram"}))  b := must(net.ListenUnixgram("unixgram", &net.UnixAddr{Name: filepath.Join(d, "b"), Net: "unixgram"}))  check(a.SetDeadline(time.Now().Add(3 * time.Second)))  check(b.SetDeadline(time.Now().Add(3 * time.Second)))  return a, b, func() { a.Close(); b.Close(); clean() }}
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