sock

package module
v0.1.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 2, 2026 License: MIT Imports: 16 Imported by: 0

README

sock

Go Reference Go Report Card Codecov

Zero-allocation socket types and address machinery for Unix systems in Go.

Language: English | 简体中文 | Español | 日本語 | Français

When to Use This Package

Use sock instead of the standard net package when you need:

  • Zero-allocation hot paths — Sockaddr types encode directly to kernel format without heap allocation
  • Non-blocking I/O — Operations return iox.ErrWouldBlock immediately instead of blocking goroutines
  • Direct kernel control — Socket options, TCP_INFO, and other low-level features
  • io_uring integration — All sockets expose iofd.FD for async I/O

For typical applications where latency is not critical, the standard net package provides a simpler and more portable API.

Features

  • Zero-Allocation Addresses — Sockaddr types encode directly to kernel format without heap allocation
  • Protocol Support — TCP, UDP, SCTP, Unix (stream/dgram/seqpacket), Raw IP
  • io_uring Ready — All sockets expose iofd.FD for async I/O integration
  • Zero-Overhead Syscalls — Direct kernel interaction via zcall assembly

Architecture

Sockaddr Interface

The Sockaddr interface is the foundation of zero-allocation address handling:

type Sockaddr interface {
    Raw() (unsafe.Pointer, uint32)  // Direct kernel format
    Family() uint16                  // AF_INET, AF_INET6, AF_UNIX
}

Address types (SockaddrInet4, SockaddrInet6, SockaddrUnix) embed raw kernel structures and return pointers directly—no marshaling, no allocation.

Socket Type Hierarchy
NetSocket (base)
├── TCPSocket → TCPConn, TCPListener
├── UDPSocket → UDPConn
├── SCTPSocket → SCTPConn, SCTPListener (Linux)
├── UnixSocket → UnixConn, UnixListener
└── RawSocket → RawConn (CAP_NET_RAW)

All sockets expose FD() *iofd.FD for integration with io_uring and other async I/O mechanisms.

Kernel Integration
Application
    ↓
sock.TCPConn.Write(data)
    ↓
iofd.FD.Write()
    ↓
zcall.Write() ← Assembly entry point (no Go runtime)
    ↓
Linux Kernel

The zcall package provides raw syscall entry points that bypass Go's runtime hooks, eliminating scheduler overhead for latency-critical paths.

Adaptive I/O Semantics

The package implements the Strike-Spin-Adapt model for non-blocking I/O:

  1. Strike: Direct syscall execution (non-blocking)
  2. Spin: Hardware-level synchronization (handled by sox if needed)
  3. Adapt: Software backoff via iox.Backoff when deadlines are set

Key behaviors:

  • Non-blocking by default: Read, Write, Accept, and Dial operations return immediately with iox.ErrWouldBlock if the kernel is not ready.
  • Deadline-driven adaptation: Only when a deadline is explicitly set (via SetDeadline, SetReadDeadline, or SetWriteDeadline) does the operation enter a retry loop with progressive backoff.
  • Non-blocking Dial: Unlike net.Dial, functions like DialTCP4 return immediately once the connection attempt starts. The TCP handshake may still be in progress (ErrInProgress is silently ignored). Use TCPDialer with a timeout for blocking behavior:
// Non-blocking (returns immediately, handshake may be in progress)
conn, _ := sock.DialTCP4(nil, raddr)

// Blocking with timeout (waits for connection or timeout)
dialer := &sock.TCPDialer{Timeout: 5 * time.Second}
conn, _ := dialer.Dial4(nil, raddr)

Installation

go get code.hybscloud.com/sock

Usage

TCP
// Server
ln, _ := sock.ListenTCP4(&sock.TCPAddr{IP: net.ParseIP("0.0.0.0"), Port: 8080})
conn, _ := ln.Accept()
conn.Read(buf)
conn.Close()

// Client
conn, _ := sock.DialTCP4(nil, &sock.TCPAddr{IP: net.ParseIP("127.0.0.1"), Port: 8080})
conn.SetNoDelay(true)
conn.Write(data)
UDP
// Server
conn, _ := sock.ListenUDP4(&sock.UDPAddr{Port: 5353})
n, addr, _ := conn.ReadFrom(buf)
conn.WriteTo(response, addr)

// Client
conn, _ := sock.DialUDP4(nil, &sock.UDPAddr{IP: net.ParseIP("8.8.8.8"), Port: 53})
conn.Write(query)
conn.Read(response)
SCTP (Linux only)
// Server
ln, _ := sock.ListenSCTP4(&sock.SCTPAddr{IP: net.ParseIP("0.0.0.0"), Port: 9000})
conn, _ := ln.Accept()
conn.Read(buf)

// Client with timeout
dialer := &sock.SCTPDialer{Timeout: 5 * time.Second}
conn, _ := dialer.Dial4(nil, &sock.SCTPAddr{IP: net.ParseIP("127.0.0.1"), Port: 9000})
conn.Write(data)
Unix Domain Sockets
// Stream
ln, _ := sock.ListenUnix("unix", &net.UnixAddr{Name: "/tmp/app.sock"})
conn, _ := ln.Accept()

// Datagram
conn, _ := sock.ListenUnixgram("unixgram", &net.UnixAddr{Name: "/tmp/app.dgram"})

// Socket pair
pair, _ := sock.UnixConnPair("unix")
pair[0].Write([]byte("ping"))
pair[1].Read(buf)
Raw Sockets (requires CAP_NET_RAW)
// ICMP ping
sock, _ := sock.NewICMPSocket4()
sock.SendTo(icmpPacket, &net.IPAddr{IP: net.ParseIP("8.8.8.8")})
n, addr, _ := sock.RecvFrom(buf)
Socket Options
// TCP tuning
conn.SetNoDelay(true)              // Disable Nagle's algorithm
conn.SetKeepAlive(true)            // Enable keepalive probes
conn.SetKeepAlivePeriod(30 * time.Second)

// Buffer sizes
sock.SetSendBuffer(conn.FD(), 256*1024)
sock.SetRecvBuffer(conn.FD(), 256*1024)

// SO_LINGER for immediate RST on close
sock.SetLinger(conn.FD(), true, 0)
Error Handling
// Non-blocking read with iox.ErrWouldBlock
n, err := conn.Read(buf)
if err == iox.ErrWouldBlock {
    // Kernel not ready, integrate with event loop or retry later
    return
}
if err != nil {
    // Real error (connection reset, closed, etc.)
    return
}

// Blocking read with deadline
conn.SetReadDeadline(time.Now().Add(5 * time.Second))
n, err = conn.Read(buf)
if err == sock.ErrTimedOut {
    // Deadline exceeded
}
Compatibility with net Package

The package provides seamless conversion with Go's standard net types:

// Convert net.TCPAddr to Sockaddr (zero-allocation)
netAddr := &net.TCPAddr{IP: net.ParseIP("127.0.0.1"), Port: 8080}
sockaddr := sock.TCPAddrToSockaddr(netAddr)

// Convert back to net.TCPAddr
tcpAddr := sock.SockaddrToTCPAddr(sockaddr)

// Type aliases for compatibility
var _ sock.Conn = conn      // net.Conn compatible
var _ sock.Addr = addr      // net.Addr compatible

// Note: Listeners return concrete types (*TCPConn, *UnixConn) for
// zero-allocation performance, not net.Conn as net.Listener requires.

Supported Platforms

Platform Status
linux/amd64 Full
linux/arm64 Full
linux/riscv64 Full
linux/loong64 Full
darwin/arm64 Partial (no SCTP, TCPInfo, multicast, SCM_RIGHTS)
freebsd/amd64 Cross-compile only

License

MIT — see LICENSE.

©2025 Hayabusa Cloud Co., Ltd.

Documentation

Overview

Package sock provides zero-allocation socket types and address machinery for Unix systems in Go.

This package is designed for ultra-low latency systems where every nanosecond matters. Unlike the standard net package, sock uses direct syscalls via the zcall assembly package, bypassing Go's runtime hooks entirely.

When to Use This Package

Use sock instead of net when you need:

  • Zero-allocation hot paths for address handling
  • Non-blocking I/O without goroutine-per-connection overhead
  • Direct control over socket options and kernel interaction
  • Integration with io_uring for async I/O (via iofd.FD)

For typical applications where latency is not critical, the standard net package provides a simpler and more portable API.

Adaptive I/O Model

All I/O operations follow the Strike-Spin-Adapt model:

  1. Strike: Direct syscall execution (non-blocking)
  2. Spin: Hardware-level synchronization (handled by caller if needed)
  3. Adapt: Software backoff via iox.Backoff when deadlines are set

By default, operations are non-blocking:

conn, _ := sock.DialTCP4(nil, raddr)
n, err := conn.Read(buf)
if err == iox.ErrWouldBlock {
    // Kernel not ready, try again later (no blocking)
}

When a deadline is set, operations retry with progressive backoff:

conn.SetReadDeadline(time.Now().Add(5 * time.Second))
n, err := conn.Read(buf)  // Retries until data or timeout
if err == sock.ErrTimedOut {
    // Deadline exceeded
}

Error Semantics

Errors follow a layered semantic model:

  • iox.ErrWouldBlock: Control flow signal, not a failure. The operation cannot complete without blocking. Retry when the kernel is ready.
  • ErrTimedOut: Deadline exceeded during adaptive retry.
  • ErrInProgress: Connection attempt started but handshake incomplete. For non-blocking dial, this is expected behavior.
  • Other errors: Actual failures (connection refused, reset, etc.)

Architecture

The Sockaddr interface is the foundation of zero-allocation address handling:

type Sockaddr interface {
    Raw() (unsafe.Pointer, uint32)  // Direct kernel format
    Family() uint16                  // AF_INET, AF_INET6, AF_UNIX
}

Address types (SockaddrInet4, SockaddrInet6, SockaddrUnix) embed raw kernel structures and return pointers directly—no marshaling, no allocation.

Socket Types

All sockets expose iofd.FD via the FD() method for io_uring integration and other async I/O mechanisms.

Compatibility

Address conversion functions bridge with the standard net package:

Type aliases (Conn, Addr, Listener) provide net.Conn, net.Addr, net.Listener interface compatibility.

Platforms

  • linux/amd64, linux/arm64, linux/riscv64, linux/loong64: Full support
  • darwin/arm64: Partial (no SCTP, TCPInfo, multicast, SCM_RIGHTS)
  • freebsd/amd64: Cross-compile only

Index

Constants

View Source
const (
	EAGAIN          = uintptr(zcall.EAGAIN)
	EWOULDBLOCK     = uintptr(zcall.EWOULDBLOCK)
	EBADF           = uintptr(zcall.EBADF)
	EINVAL          = uintptr(zcall.EINVAL)
	EINTR           = uintptr(zcall.EINTR)
	ENOMEM          = uintptr(zcall.ENOMEM)
	EACCES          = uintptr(zcall.EACCES)
	EPERM           = uintptr(zcall.EPERM)
	EADDRINUSE      = uintptr(zcall.EADDRINUSE)
	EADDRNOTAVAIL   = uintptr(zcall.EADDRNOTAVAIL)
	ECONNREFUSED    = uintptr(zcall.ECONNREFUSED)
	ECONNRESET      = uintptr(zcall.ECONNRESET)
	ENOTCONN        = uintptr(zcall.ENOTCONN)
	EDESTADDRREQ    = uintptr(zcall.EDESTADDRREQ)
	EMSGSIZE        = uintptr(zcall.EMSGSIZE)
	ETIMEDOUT       = uintptr(zcall.ETIMEDOUT)
	ENETDOWN        = uintptr(zcall.ENETDOWN)
	ENETUNREACH     = uintptr(zcall.ENETUNREACH)
	EHOSTUNREACH    = uintptr(zcall.EHOSTUNREACH)
	ESHUTDOWN       = uintptr(zcall.ESHUTDOWN)
	EINPROGRESS     = uintptr(zcall.EINPROGRESS)
	ECONNABORTED    = uintptr(zcall.ECONNABORTED)
	EALREADY        = uintptr(zcall.EALREADY)
	EISCONN         = uintptr(zcall.EISCONN)
	EPIPE           = uintptr(zcall.EPIPE)
	ENOBUFS         = uintptr(zcall.ENOBUFS)
	EAFNOSUPPORT    = uintptr(zcall.EAFNOSUPPORT)
	EPROTONOSUPPORT = uintptr(zcall.EPROTONOSUPPORT)
)

Errno constants for common error codes. These are aliased from zcall for cross-platform compatibility.

View Source
const (
	F_GETFD    = 1
	F_SETFD    = 2
	F_GETFL    = 3
	F_SETFL    = 4
	FD_CLOEXEC = 1
)

fcntl command constants for Linux. These are consistent across all Linux architectures.

View Source
const (
	IP_MULTICAST_IF    = 32
	IP_MULTICAST_TTL   = 33
	IP_MULTICAST_LOOP  = 34
	IP_ADD_MEMBERSHIP  = 35
	IP_DROP_MEMBERSHIP = 36
)

IPv4 multicast socket options.

View Source
const (
	IPV6_MULTICAST_IF    = 17
	IPV6_MULTICAST_HOPS  = 18
	IPV6_MULTICAST_LOOP  = 19
	IPV6_ADD_MEMBERSHIP  = 20
	IPV6_DROP_MEMBERSHIP = 21
	IPV6_MULTICAST_ALL   = 29
)

IPv6 multicast socket options.

View Source
const (
	SOCK_STREAM    = zcall.SOCK_STREAM
	SOCK_DGRAM     = zcall.SOCK_DGRAM
	SOCK_RAW       = zcall.SOCK_RAW
	SOCK_SEQPACKET = zcall.SOCK_SEQPACKET
	SOCK_NONBLOCK  = zcall.SOCK_NONBLOCK
	SOCK_CLOEXEC   = zcall.SOCK_CLOEXEC
)

Socket type constants (SOCK_*) - aliased from zcall for platform compatibility.

View Source
const (
	IPPROTO_IP     = zcall.IPPROTO_IP
	IPPROTO_ICMP   = zcall.IPPROTO_ICMP
	IPPROTO_TCP    = zcall.IPPROTO_TCP
	IPPROTO_UDP    = zcall.IPPROTO_UDP
	IPPROTO_IPV6   = zcall.IPPROTO_IPV6
	IPPROTO_ICMPV6 = 58 // Consistent across platforms
	IPPROTO_RAW    = zcall.IPPROTO_RAW
)

Protocol constants (IPPROTO_*) - aliased from zcall for platform compatibility.

View Source
const (
	SOL_SOCKET = zcall.SOL_SOCKET
	SOL_IP     = zcall.SOL_IP
	SOL_TCP    = zcall.SOL_TCP
	SOL_UDP    = zcall.SOL_UDP
	SOL_IPV6   = zcall.SOL_IPV6
)

Socket option levels (SOL_*) - aliased from zcall for platform compatibility.

View Source
const (
	SO_REUSEADDR = zcall.SO_REUSEADDR
	SO_REUSEPORT = zcall.SO_REUSEPORT
	SO_KEEPALIVE = zcall.SO_KEEPALIVE
	SO_BROADCAST = zcall.SO_BROADCAST
	SO_SNDBUF    = zcall.SO_SNDBUF
	SO_RCVBUF    = zcall.SO_RCVBUF
	SO_ERROR     = zcall.SO_ERROR
	SO_TYPE      = zcall.SO_TYPE
	SO_LINGER    = zcall.SO_LINGER
	SO_RCVTIMEO  = zcall.SO_RCVTIMEO
	SO_SNDTIMEO  = zcall.SO_SNDTIMEO
)

Socket options (SO_*) - aliased from zcall for platform compatibility.

View Source
const (
	TCP_NODELAY   = zcall.TCP_NODELAY
	TCP_KEEPINTVL = zcall.TCP_KEEPINTVL
	TCP_KEEPCNT   = zcall.TCP_KEEPCNT
)

TCP options (TCP_*) - aliased from zcall for platform compatibility.

View Source
const (
	SHUT_RD   = zcall.SHUT_RD
	SHUT_WR   = zcall.SHUT_WR
	SHUT_RDWR = zcall.SHUT_RDWR
)

Shutdown constants (SHUT_*) - aliased from zcall for platform compatibility.

View Source
const (
	MSG_OOB       = zcall.MSG_OOB
	MSG_PEEK      = zcall.MSG_PEEK
	MSG_DONTROUTE = zcall.MSG_DONTROUTE
	MSG_TRUNC     = zcall.MSG_TRUNC
	MSG_DONTWAIT  = zcall.MSG_DONTWAIT
	MSG_WAITALL   = zcall.MSG_WAITALL
)

Message flags (MSG_*) - aliased from zcall for platform compatibility.

View Source
const (
	O_RDONLY   = zcall.O_RDONLY
	O_WRONLY   = zcall.O_WRONLY
	O_RDWR     = zcall.O_RDWR
	O_NONBLOCK = zcall.O_NONBLOCK
	O_CLOEXEC  = zcall.O_CLOEXEC
)

File descriptor flags - aliased from zcall for platform compatibility.

View Source
const (
	IPPROTO_SCTP    = zcall.IPPROTO_SCTP
	IPPROTO_UDPLITE = 136
)

Linux-specific IPPROTO constants.

View Source
const (
	SO_DEBUG        = zcall.SO_DEBUG
	SO_DONTROUTE    = zcall.SO_DONTROUTE
	SO_OOBINLINE    = zcall.SO_OOBINLINE
	SO_INCOMING_CPU = zcall.SO_INCOMING_CPU
	SO_ZEROCOPY     = zcall.SO_ZEROCOPY
)

Linux-specific socket options (SO_*).

View Source
const (
	TCP_MAXSEG        = zcall.TCP_MAXSEG
	TCP_CORK          = zcall.TCP_CORK
	TCP_KEEPIDLE      = zcall.TCP_KEEPIDLE
	TCP_SYNCNT        = zcall.TCP_SYNCNT
	TCP_LINGER2       = zcall.TCP_LINGER2
	TCP_DEFER_ACCEPT  = zcall.TCP_DEFER_ACCEPT
	TCP_WINDOW_CLAMP  = zcall.TCP_WINDOW_CLAMP
	TCP_INFO          = zcall.TCP_INFO
	TCP_QUICKACK      = zcall.TCP_QUICKACK
	TCP_CONGESTION    = zcall.TCP_CONGESTION
	TCP_FASTOPEN      = zcall.TCP_FASTOPEN
	TCP_NOTSENT_LOWAT = zcall.TCP_NOTSENT_LOWAT
)

Linux-specific TCP options (TCP_*).

View Source
const (
	MSG_CTRUNC       = zcall.MSG_CTRUNC
	MSG_EOR          = zcall.MSG_EOR
	MSG_NOSIGNAL     = zcall.MSG_NOSIGNAL
	MSG_MORE         = zcall.MSG_MORE
	MSG_WAITFORONE   = zcall.MSG_WAITFORONE
	MSG_FASTOPEN     = zcall.MSG_FASTOPEN
	MSG_CMSG_CLOEXEC = zcall.MSG_CMSG_CLOEXEC
	MSG_ZEROCOPY     = zcall.MSG_ZEROCOPY
)

Linux-specific message flags (MSG_*).

View Source
const (
	POLLIN   = zcall.POLLIN
	POLLPRI  = zcall.POLLPRI
	POLLOUT  = zcall.POLLOUT
	POLLERR  = zcall.POLLERR
	POLLHUP  = zcall.POLLHUP
	POLLNVAL = zcall.POLLNVAL
)

Linux-specific poll event constants.

View Source
const (
	O_CREAT  = zcall.O_CREAT
	O_EXCL   = zcall.O_EXCL
	O_NOCTTY = zcall.O_NOCTTY
	O_TRUNC  = zcall.O_TRUNC
	O_APPEND = zcall.O_APPEND
	O_SYNC   = zcall.O_SYNC
	O_DIRECT = zcall.O_DIRECT
)

Linux-specific file descriptor flags.

View Source
const (
	SCM_RIGHTS      = 0x01 // File descriptor passing
	SCM_CREDENTIALS = 0x02 // Process credentials
	SCM_SECURITY    = 0x03 // Security label
	SCM_PIDFD       = 0x04 // PID file descriptor
)

Socket-level control message types.

View Source
const (
	SizeofSockaddrInet4 = 16
	SizeofSockaddrInet6 = 28
	SizeofSockaddrUnix  = 110
	SizeofSockaddrAny   = 128
)

Size constants for socket address structures.

View Source
const (
	AF_UNSPEC = zcall.AF_UNIX - zcall.AF_UNIX // 0
	AF_UNIX   = zcall.AF_UNIX
	AF_LOCAL  = zcall.AF_LOCAL
	AF_INET   = zcall.AF_INET
	AF_INET6  = zcall.AF_INET6
)

Address family constants - aliases to zcall for convenience.

View Source
const (
	SCTP_RTOINFO             = 0
	SCTP_ASSOCINFO           = 1
	SCTP_INITMSG             = 2
	SCTP_NODELAY             = 3
	SCTP_AUTOCLOSE           = 4
	SCTP_SET_PEER_PRIMARY    = 5
	SCTP_PRIMARY_ADDR        = 6
	SCTP_ADAPTATION_LAYER    = 7
	SCTP_DISABLE_FRAGMENTS   = 8
	SCTP_PEER_ADDR_PARAMS    = 9
	SCTP_DEFAULT_SEND_PARAM  = 10
	SCTP_EVENTS              = 11
	SCTP_I_WANT_MAPPED_V4    = 12
	SCTP_MAXSEG              = 13
	SCTP_STATUS              = 14
	SCTP_GET_PEER_ADDR_INFO  = 15
	SCTP_DELAYED_ACK_TIME    = 16
	SCTP_DELAYED_SACK        = SCTP_DELAYED_ACK_TIME
	SCTP_CONTEXT             = 17
	SCTP_FRAGMENT_INTERLEAVE = 18
	SCTP_PARTIAL_DELIVERY    = 19
	SCTP_MAX_BURST           = 20
	SCTP_HMAC_IDENT          = 22
	SCTP_AUTH_ACTIVE_KEY     = 24
	SCTP_AUTO_ASCONF         = 30
	SCTP_PEER_ADDR_THLDS     = 31
)

SCTP socket option constants. Reference: /usr/include/netinet/sctp.h

View Source
const (
	TCP_ESTABLISHED = 1
	TCP_SYN_SENT    = 2
	TCP_SYN_RECV    = 3
	TCP_FIN_WAIT1   = 4
	TCP_FIN_WAIT2   = 5
	TCP_TIME_WAIT   = 6
	TCP_CLOSE       = 7
	TCP_CLOSE_WAIT  = 8
	TCP_LAST_ACK    = 9
	TCP_LISTEN      = 10
	TCP_CLOSING     = 11
)

TCP states from Linux kernel.

View Source
const (
	TCP_CA_Open     = 0 // Normal operation
	TCP_CA_Disorder = 1 // DUPACKs or SACKs received
	TCP_CA_CWR      = 2 // ECN congestion window reduction
	TCP_CA_Recovery = 3 // Fast recovery in progress
	TCP_CA_Loss     = 4 // Loss recovery (RTO)
)

TCP congestion avoidance states.

View Source
const (
	TCPI_OPT_TIMESTAMPS = 1  // Timestamps enabled
	TCPI_OPT_SACK       = 2  // SACK enabled
	TCPI_OPT_WSCALE     = 4  // Window scaling enabled
	TCPI_OPT_ECN        = 8  // ECN was negotiated
	TCPI_OPT_ECN_SEEN   = 16 // At least one ECT packet received
	TCPI_OPT_SYN_DATA   = 32 // SYN-ACK acked SYN data
	TCPI_OPT_USEC_TS    = 64 // Microsecond timestamps
)

TCPI_OPT_* option flags.

View Source
const DefaultBacklog = 511

Default backlog for listen().

View Source
const (
	IPV6_V6ONLY = zcall.IPV6_V6ONLY
)

Linux-specific IPv6 options (IPV6_*).

View Source
const SYS_FCNTL = 72

SYS_FCNTL is the syscall number for fcntl on Linux amd64.

View Source
const SizeofCmsghdr = 16

SizeofCmsghdr is the size of Cmsghdr.

View Source
const SizeofMsghdr = 56

SizeofMsghdr is the size of zcall.Msghdr.

View Source
const SizeofTCPInfo = 280

SizeofTCPInfo is the size of the TCPInfo structure. This matches the Linux kernel's struct tcp_info (kernel 6.12+).

View Source
const SizeofUcred = 12

SizeofUcred is the size of Ucred.

Variables

View Source
var (
	// ErrAddressInUse indicates the address is already bound (EADDRINUSE).
	// Common when restarting a server without SO_REUSEADDR.
	ErrAddressInUse = errors.New("sock: address in use")

	// ErrAddressNotAvailable indicates the requested address is not available (EADDRNOTAVAIL).
	// Occurs when binding to a non-local IP or invalid interface.
	ErrAddressNotAvailable = errors.New("sock: address not available")

	// ErrConnectionRefused indicates the target actively refused the connection (ECONNREFUSED).
	// No service is listening on the specified port.
	ErrConnectionRefused = errors.New("sock: connection refused")

	// ErrConnectionReset indicates the connection was reset by the peer (ECONNRESET, ECONNABORTED, EPIPE).
	// The remote end closed the connection unexpectedly.
	ErrConnectionReset = errors.New("sock: connection reset")

	// ErrNotConnected indicates the socket is not connected (ENOTCONN, EDESTADDRREQ).
	// Returned when calling Read/Write on an unconnected socket without an address.
	ErrNotConnected = errors.New("sock: not connected")

	// ErrTimedOut indicates the operation exceeded its deadline (ETIMEDOUT).
	// Returned by adaptive I/O when the deadline set via SetDeadline is exceeded.
	ErrTimedOut = errors.New("sock: timed out")

	// ErrNetworkUnreachable indicates the network is unreachable (ENETUNREACH, ENETDOWN).
	// No route exists to the destination network.
	ErrNetworkUnreachable = errors.New("sock: network unreachable")

	// ErrHostUnreachable indicates the host is unreachable (EHOSTUNREACH).
	// The specific host cannot be reached, even though the network is reachable.
	ErrHostUnreachable = errors.New("sock: host unreachable")

	// ErrMessageTooLarge indicates the message is too large for the transport (EMSGSIZE).
	// For UDP, this means the datagram exceeds the MTU.
	ErrMessageTooLarge = errors.New("sock: message too large")

	// ErrProtocolNotSupported indicates the protocol is not supported (EPROTONOSUPPORT).
	// For example, SCTP on systems without kernel SCTP support.
	ErrProtocolNotSupported = errors.New("sock: protocol not supported")

	// ErrAddressFamilyNotSupported indicates the address family is not supported (EAFNOSUPPORT).
	// For example, IPv6 on systems without IPv6 support.
	ErrAddressFamilyNotSupported = errors.New("sock: address family not supported")

	// ErrUnknownNetwork indicates an unrecognized network string was provided.
	// Valid networks: "ip", "ip4", "ip6" for raw sockets.
	ErrUnknownNetwork = errors.New("sock: unknown network")
)

Socket-specific errors for network operations.

These errors map from Linux kernel errno values to semantic Go errors. Use errors.Is() to check for specific error conditions:

if errors.Is(err, sock.ErrConnectionRefused) {
    // Handle connection refused
}
View Source
var (
	// IPV4zero is an IPv4 address representing the zero value (0.0.0.0).
	IPV4zero = net.IPv4zero

	// IPV6unspecified is an IPv6 address representing the unspecified value (::).
	IPV6unspecified = net.IPv6unspecified

	// IPv4LoopBack is an IPv4 address representing the loopback address (127.0.0.1).
	IPv4LoopBack = net.IPv4(127, 0, 0, 1)

	// IPv6LoopBack is an IPv6 address representing the loopback address (::).
	IPv6LoopBack = net.IPv6loopback
)
View Source
var (
	// TCPAddrFromAddrPort refers to the net.TCPAddrFromAddrPort function
	// It returns addr as a [TCPAddr]. If addr.IsValid() is false,
	// then the returned TCPAddr will contain a nil IP field, indicating an
	// address-family-agnostic unspecified address.
	TCPAddrFromAddrPort = net.TCPAddrFromAddrPort

	// UDPAddrFromAddrPort refers to the net.UDPAddrFromAddrPort function
	// It returns addr as a UDPAddr. If addr.IsValid() is false,
	// then the returned UDPAddr will contain a nil IP field, indicating an
	// address-family-agnostic unspecified address.
	UDPAddrFromAddrPort = net.UDPAddrFromAddrPort
)
View Source
var (
	// ResolveIPAddr refers to the net.ResolveIPAddr function
	// It returns an address of the IP end point.
	ResolveIPAddr = net.ResolveIPAddr

	// ResolveTCPAddr refers to the net.ResolveTCPAddr function.
	// It returns a TCPAddr struct that contains IP and port information.
	ResolveTCPAddr = net.ResolveTCPAddr

	// ResolveUDPAddr refers to the net.ResolveUDPAddr function.
	// It takes a network type and a string representation of the address and returns a
	// UDPAddr struct that contains the IP and port information.
	ResolveUDPAddr = net.ResolveUDPAddr
)
View Source
var (
	ErrInvalidParam = iofd.ErrInvalidParam
	ErrInterrupted  = iofd.ErrInterrupted
	ErrNoMemory     = iofd.ErrNoMemory
	ErrPermission   = iofd.ErrPermission
)

Common errors reused from iofd for semantic consistency.

View Source
var (
	ErrInProgress   = errors.New("sock: operation in progress")
	ErrNotSupported = errors.New("sock: operation not supported")
)

Socket-specific errors.

View Source
var (
	DefaultResolver  = net.DefaultResolver
	NetworkByteOrder = binary.BigEndian
)
View Source
var ErrClosed = iofd.ErrClosed

ErrClosed indicates the socket or file descriptor has been closed. Reused from iofd for semantic consistency across the ecosystem.

Functions

func CmsgAlign

func CmsgAlign(length int) int

CmsgAlign aligns a length to the proper boundary.

func CmsgData

func CmsgData(cmsg *Cmsghdr) unsafe.Pointer

CmsgData returns a pointer to the data portion of a control message.

func CmsgLen

func CmsgLen(length int) int

CmsgLen returns the length field value for a control message with given data length.

func CmsgSpace

func CmsgSpace(length int) int

CmsgSpace returns the space needed for a control message with given data length.

func GetIPv6Only

func GetIPv6Only(fd *iofd.FD) (bool, error)

GetIPv6Only returns the current IPV6_V6ONLY setting.

func GetKeepAlive

func GetKeepAlive(fd *iofd.FD) (bool, error)

GetKeepAlive returns the current SO_KEEPALIVE setting.

func GetLinger

func GetLinger(fd *iofd.FD) (bool, int, error)

GetLinger returns the current SO_LINGER setting. Returns (enabled, seconds, error).

func GetMulticast6Hops

func GetMulticast6Hops(fd *iofd.FD) (int, error)

GetMulticast6Hops returns the current IPv6 multicast hop limit.

func GetMulticast6Interface

func GetMulticast6Interface(fd *iofd.FD) (int, error)

GetMulticast6Interface returns the current IPv6 multicast output interface.

func GetMulticast6Loop

func GetMulticast6Loop(fd *iofd.FD) (bool, error)

GetMulticast6Loop returns whether IPv6 multicast loopback is enabled.

func GetMulticastLoop

func GetMulticastLoop(fd *iofd.FD) (bool, error)

GetMulticastLoop returns whether IPv4 multicast loopback is enabled.

func GetMulticastTTL

func GetMulticastTTL(fd *iofd.FD) (int, error)

GetMulticastTTL returns the current IPv4 multicast TTL.

func GetRecvBuffer

func GetRecvBuffer(fd *iofd.FD) (int, error)

GetRecvBuffer returns the current SO_RCVBUF setting.

func GetReuseAddr

func GetReuseAddr(fd *iofd.FD) (bool, error)

GetReuseAddr returns the current SO_REUSEADDR setting.

func GetReusePort

func GetReusePort(fd *iofd.FD) (bool, error)

GetReusePort returns the current SO_REUSEPORT setting.

func GetSCTPAutoclose

func GetSCTPAutoclose(fd *iofd.FD) (int, error)

GetSCTPAutoclose returns the current SCTP_AUTOCLOSE setting.

func GetSCTPContext

func GetSCTPContext(fd *iofd.FD) (uint32, error)

GetSCTPContext returns the current SCTP_CONTEXT setting.

func GetSCTPDisableFragments

func GetSCTPDisableFragments(fd *iofd.FD) (bool, error)

GetSCTPDisableFragments returns the current SCTP_DISABLE_FRAGMENTS setting.

func GetSCTPFragmentInterleave

func GetSCTPFragmentInterleave(fd *iofd.FD) (int, error)

GetSCTPFragmentInterleave returns the current SCTP_FRAGMENT_INTERLEAVE setting.

func GetSCTPMappedV4

func GetSCTPMappedV4(fd *iofd.FD) (bool, error)

GetSCTPMappedV4 returns the current SCTP_I_WANT_MAPPED_V4 setting.

func GetSCTPMaxBurst

func GetSCTPMaxBurst(fd *iofd.FD) (int, error)

GetSCTPMaxBurst returns the current SCTP_MAX_BURST setting.

func GetSCTPMaxseg

func GetSCTPMaxseg(fd *iofd.FD) (int, error)

GetSCTPMaxseg returns the current SCTP_MAXSEG setting.

func GetSCTPNodelay

func GetSCTPNodelay(fd *iofd.FD) (bool, error)

GetSCTPNodelay returns the current SCTP_NODELAY setting.

func GetSCTPPartialDeliveryPoint

func GetSCTPPartialDeliveryPoint(fd *iofd.FD) (int, error)

GetSCTPPartialDeliveryPoint returns the current SCTP_PARTIAL_DELIVERY_POINT setting.

func GetSendBuffer

func GetSendBuffer(fd *iofd.FD) (int, error)

GetSendBuffer returns the current SO_SNDBUF setting.

func GetSocketError

func GetSocketError(fd *iofd.FD) error

GetSocketError retrieves and clears the pending socket error.

func GetSocketType

func GetSocketType(fd *iofd.FD) (int, error)

GetSocketType returns the socket type (SOCK_STREAM, SOCK_DGRAM, etc.).

func GetTCPCork

func GetTCPCork(fd *iofd.FD) (bool, error)

GetTCPCork returns the current TCP_CORK setting.

func GetTCPDeferAccept

func GetTCPDeferAccept(fd *iofd.FD) (int, error)

GetTCPDeferAccept returns the current TCP_DEFER_ACCEPT setting.

func GetTCPFastOpen

func GetTCPFastOpen(fd *iofd.FD) (int, error)

GetTCPFastOpen returns the current TCP_FASTOPEN setting.

func GetTCPInfoInto

func GetTCPInfoInto(fd *iofd.FD, info *TCPInfo) error

GetTCPInfoInto retrieves TCP connection information into an existing TCPInfo. This avoids allocation when called repeatedly.

func GetTCPKeepCnt

func GetTCPKeepCnt(fd *iofd.FD) (int, error)

GetTCPKeepCnt returns the current TCP_KEEPCNT setting.

func GetTCPKeepIdle

func GetTCPKeepIdle(fd *iofd.FD) (int, error)

GetTCPKeepIdle returns the current TCP_KEEPIDLE setting.

func GetTCPKeepIntvl

func GetTCPKeepIntvl(fd *iofd.FD) (int, error)

GetTCPKeepIntvl returns the current TCP_KEEPINTVL setting.

func GetTCPNoDelay

func GetTCPNoDelay(fd *iofd.FD) (bool, error)

GetTCPNoDelay returns the current TCP_NODELAY setting.

func GetTCPQuickAck

func GetTCPQuickAck(fd *iofd.FD) (bool, error)

GetTCPQuickAck returns the current TCP_QUICKACK setting.

func GetZeroCopy

func GetZeroCopy(fd *iofd.FD) (bool, error)

GetZeroCopy returns the current SO_ZEROCOPY setting.

func IP4AddressToBytes

func IP4AddressToBytes(ip net.IP) [4]byte

IP4AddressToBytes converts an IPv4 address to a byte array. If the given IP address is not an IPv4 address, it returns an empty byte array. The byte array contains the four octets of the IPv4 address in network byte order.

func IP6AddressToBytes

func IP6AddressToBytes(ip net.IP) [16]byte

IP6AddressToBytes converts the given net.IPv6 address to a fixed-size byte array. The resulting byte array contains the individual bytes of the IPv6 address in the same order as the original address. Each byte of the byte array corresponds to a byte of the IPv6 address. For example, the first byte of the byte array corresponds to the first byte of the IPv6 address, and so on. The byte array has a length of 16 bytes.

Note: This function assumes that the given net.IPv6 address is a valid IPv6 address.

func JoinMulticast4

func JoinMulticast4(fd *iofd.FD, mcastAddr, ifAddr [4]byte) error

JoinMulticast4 joins an IPv4 multicast group. mcastAddr is the multicast group address (e.g., 224.0.0.1). ifAddr is the local interface address to use (0.0.0.0 for default).

func JoinMulticast4n

func JoinMulticast4n(fd *iofd.FD, mcastAddr [4]byte, ifindex int) error

JoinMulticast4n joins an IPv4 multicast group using interface index. ifindex of 0 uses the default interface.

func JoinMulticast6

func JoinMulticast6(fd *iofd.FD, mcastAddr [16]byte, ifindex int) error

JoinMulticast6 joins an IPv6 multicast group. ifindex of 0 uses the default interface.

func LeaveMulticast4

func LeaveMulticast4(fd *iofd.FD, mcastAddr, ifAddr [4]byte) error

LeaveMulticast4 leaves an IPv4 multicast group.

func LeaveMulticast4n

func LeaveMulticast4n(fd *iofd.FD, mcastAddr [4]byte, ifindex int) error

LeaveMulticast4n leaves an IPv4 multicast group using interface index.

func LeaveMulticast6

func LeaveMulticast6(fd *iofd.FD, mcastAddr [16]byte, ifindex int) error

LeaveMulticast6 leaves an IPv6 multicast group.

func ParseUnixRights

func ParseUnixRights(buf []byte) []int

ParseUnixRights extracts file descriptors from a received control message buffer.

func RecvFDs

func RecvFDs(fd *iofd.FD, dataBuf []byte, maxFDs int) (int, []int, error)

RecvFDs receives file descriptors from a Unix socket. Returns the received data, file descriptors, and any error.

func RecvMsg

func RecvMsg(fd *iofd.FD, msg *Msghdr, flags int) (int, error)

RecvMsg receives a message from a socket.

func ResolveUnixAddr

func ResolveUnixAddr(network, address string) (*net.UnixAddr, error)

ResolveUnixAddr returns an address of Unix domain socket. The network must be "unix", "unixgram", or "unixpacket".

func SendFDs

func SendFDs(fd *iofd.FD, fds []int, data []byte) (int, error)

SendFDs sends file descriptors over a Unix socket. The data parameter can be empty but at least 1 byte is typically sent.

func SendMsg

func SendMsg(fd *iofd.FD, msg *Msghdr, flags int) (int, error)

SendMsg sends a message on a socket.

func SetCloseOnExec

func SetCloseOnExec(fd *iofd.FD, cloexec bool) error

SetCloseOnExec sets the FD_CLOEXEC flag on the file descriptor.

func SetIPv6Only

func SetIPv6Only(fd *iofd.FD, enable bool) error

SetIPv6Only enables or disables the IPV6_V6ONLY socket option. When enabled, restricts the socket to IPv6 communication only.

func SetKeepAlive

func SetKeepAlive(fd *iofd.FD, enable bool) error

SetKeepAlive enables or disables the SO_KEEPALIVE socket option. When enabled, the socket sends keepalive probes to detect dead peers.

func SetLinger

func SetLinger(fd *iofd.FD, enable bool, secs int) error

SetLinger sets the SO_LINGER socket option. When enabled with a non-zero timeout, Close() will block until pending data is sent or the timeout expires. When enabled with zero timeout, Close() sends RST immediately. When disabled, Close() returns immediately (default).

func SetMulticast6All

func SetMulticast6All(fd *iofd.FD, enable bool) error

SetMulticast6All enables or disables receiving all multicast packets. When disabled, only packets to joined groups are received.

func SetMulticast6Hops

func SetMulticast6Hops(fd *iofd.FD, hops int) error

SetMulticast6Hops sets the IPv6 multicast hop limit. A value of 1 means packets stay on local network only. A value of -1 uses the system default.

func SetMulticast6Interface

func SetMulticast6Interface(fd *iofd.FD, ifindex int) error

SetMulticast6Interface sets the IPv6 multicast output interface.

func SetMulticast6Loop

func SetMulticast6Loop(fd *iofd.FD, enable bool) error

SetMulticast6Loop enables or disables IPv6 multicast loopback.

func SetMulticastInterface

func SetMulticastInterface(fd *iofd.FD, ifAddr [4]byte) error

SetMulticastInterface sets the IPv4 multicast output interface by address.

func SetMulticastInterfaceByIndex

func SetMulticastInterfaceByIndex(fd *iofd.FD, ifindex int) error

SetMulticastInterfaceByIndex sets the IPv4 multicast output interface by index.

func SetMulticastLoop

func SetMulticastLoop(fd *iofd.FD, enable bool) error

SetMulticastLoop enables or disables IPv4 multicast loopback. When enabled, multicast packets are looped back to local sockets.

func SetMulticastTTL

func SetMulticastTTL(fd *iofd.FD, ttl int) error

SetMulticastTTL sets the IPv4 multicast TTL (time-to-live). TTL of 1 means packets stay on local network only.

func SetNonBlock

func SetNonBlock(fd *iofd.FD, nonblock bool) error

SetNonBlock sets the O_NONBLOCK flag on the file descriptor.

func SetRecvBuffer

func SetRecvBuffer(fd *iofd.FD, size int) error

SetRecvBuffer sets the SO_RCVBUF socket option. This sets the receive buffer size in bytes.

func SetReuseAddr

func SetReuseAddr(fd *iofd.FD, enable bool) error

SetReuseAddr enables or disables the SO_REUSEADDR socket option. When enabled, allows binding to an address that is already in use.

func SetReusePort

func SetReusePort(fd *iofd.FD, enable bool) error

SetReusePort enables or disables the SO_REUSEPORT socket option. When enabled, allows multiple sockets to bind to the same port. The kernel distributes incoming connections among the sockets.

func SetSCTPAutoclose

func SetSCTPAutoclose(fd *iofd.FD, secs int) error

SetSCTPAutoclose sets the SCTP_AUTOCLOSE option. When set to a non-zero value, idle associations are closed after the specified number of seconds.

func SetSCTPContext

func SetSCTPContext(fd *iofd.FD, context uint32) error

SetSCTPContext sets the SCTP_CONTEXT option. This sets the default context value for outgoing messages.

func SetSCTPDisableFragments

func SetSCTPDisableFragments(fd *iofd.FD, disable bool) error

SetSCTPDisableFragments enables or disables the SCTP_DISABLE_FRAGMENTS option. When enabled, SCTP will not fragment messages.

func SetSCTPFragmentInterleave

func SetSCTPFragmentInterleave(fd *iofd.FD, level int) error

SetSCTPFragmentInterleave sets the SCTP_FRAGMENT_INTERLEAVE option. 0 = no interleaving, 1 = interleave same association, 2 = full interleave

func SetSCTPInitMsg

func SetSCTPInitMsg(fd *iofd.FD, msg *SCTPInitMsg) error

SetSCTPInitMsg sets the SCTP_INITMSG option for association initialization. This configures the default number of streams and retransmission parameters.

func SetSCTPMappedV4

func SetSCTPMappedV4(fd *iofd.FD, enable bool) error

SetSCTPMappedV4 enables or disables IPv4 mapped addresses.

func SetSCTPMaxBurst

func SetSCTPMaxBurst(fd *iofd.FD, burst int) error

SetSCTPMaxBurst sets the SCTP_MAX_BURST option. This limits the number of packets that can be sent in a burst.

func SetSCTPMaxseg

func SetSCTPMaxseg(fd *iofd.FD, size int) error

SetSCTPMaxseg sets the SCTP_MAXSEG option. This sets the maximum segment size for SCTP packets.

func SetSCTPNodelay

func SetSCTPNodelay(fd *iofd.FD, enable bool) error

SetSCTPNodelay enables or disables the SCTP_NODELAY socket option. When enabled, disables Nagle-like algorithm for lower latency.

func SetSCTPPartialDeliveryPoint

func SetSCTPPartialDeliveryPoint(fd *iofd.FD, bytes int) error

SetSCTPPartialDeliveryPoint sets the SCTP_PARTIAL_DELIVERY_POINT option. This sets the threshold (in bytes) for partial delivery.

func SetSendBuffer

func SetSendBuffer(fd *iofd.FD, size int) error

SetSendBuffer sets the SO_SNDBUF socket option. This sets the send buffer size in bytes.

func SetTCPCork

func SetTCPCork(fd *iofd.FD, enable bool) error

SetTCPCork enables or disables the TCP_CORK socket option. When enabled, delays sending data until the cork is removed or the socket buffer is full, allowing for more efficient packet packing.

func SetTCPDeferAccept

func SetTCPDeferAccept(fd *iofd.FD, secs int) error

SetTCPDeferAccept sets the TCP_DEFER_ACCEPT socket option. This sets the time (in seconds) to wait for data after accept() before waking up the application.

func SetTCPFastOpen

func SetTCPFastOpen(fd *iofd.FD, qlen int) error

SetTCPFastOpen sets the TCP_FASTOPEN socket option. This sets the maximum length of pending SYNs for TFO (TCP Fast Open).

func SetTCPKeepCnt

func SetTCPKeepCnt(fd *iofd.FD, count int) error

SetTCPKeepCnt sets the TCP_KEEPCNT socket option. This sets the maximum number of keepalive probes before dropping the connection.

func SetTCPKeepIdle

func SetTCPKeepIdle(fd *iofd.FD, secs int) error

SetTCPKeepIdle sets the TCP_KEEPIDLE socket option. This sets the time (in seconds) the connection needs to remain idle before TCP starts sending keepalive probes.

func SetTCPKeepIntvl

func SetTCPKeepIntvl(fd *iofd.FD, secs int) error

SetTCPKeepIntvl sets the TCP_KEEPINTVL socket option. This sets the time (in seconds) between individual keepalive probes.

func SetTCPNoDelay

func SetTCPNoDelay(fd *iofd.FD, enable bool) error

SetTCPNoDelay enables or disables the TCP_NODELAY socket option. When enabled, disables Nagle's algorithm for lower latency.

func SetTCPQuickAck

func SetTCPQuickAck(fd *iofd.FD, enable bool) error

SetTCPQuickAck enables or disables the TCP_QUICKACK socket option. When enabled, sends ACKs immediately rather than delaying them.

func SetZeroCopy

func SetZeroCopy(fd *iofd.FD, enable bool) error

SetZeroCopy enables or disables the SO_ZEROCOPY socket option. When enabled, allows zero-copy transmission using MSG_ZEROCOPY flag. Requires kernel 4.14+ for TCP and 5.0+ for UDP.

func SockaddrToTCPAddr

func SockaddrToTCPAddr(sa Sockaddr) *net.TCPAddr

SockaddrToTCPAddr converts a Sockaddr to a *net.TCPAddr.

func SockaddrToUDPAddr

func SockaddrToUDPAddr(sa Sockaddr) *net.UDPAddr

SockaddrToUDPAddr converts a Sockaddr to a *net.UDPAddr.

func SockaddrToUnixAddr

func SockaddrToUnixAddr(sa Sockaddr, network string) *net.UnixAddr

SockaddrToUnixAddr converts a Sockaddr to a *net.UnixAddr.

func UnixCredentials

func UnixCredentials(cred *Ucred) []byte

UnixCredentials creates a control message buffer for passing credentials.

func UnixRights

func UnixRights(fds ...int) []byte

UnixRights creates a control message buffer for passing file descriptors. The returned buffer is properly formatted for use with sendmsg.

Types

type Addr

type Addr = net.Addr

Type aliases for net package compatibility.

type AddrError

type AddrError = net.AddrError

Type aliases for net package compatibility.

type Cmsghdr

type Cmsghdr struct {
	Len   uint64 // Data byte count, including header
	Level int32  // Originating protocol
	Type  int32  // Protocol-specific type
}

Cmsghdr represents a control message header. Matches struct cmsghdr in Linux.

type Conn

type Conn = net.Conn

Type aliases for net package compatibility.

type IP

type IP = net.IP

IP represents an IP address. It is a type alias for the net.IP type.

type IPAddr

type IPAddr = net.IPAddr

IPAddr represents a network address of type IP. It is a type alias for the net.IPAddr type.

func IPAddrFromSCTPAddr

func IPAddrFromSCTPAddr(addr *SCTPAddr) *IPAddr

IPAddrFromSCTPAddr returns a new IPAddr based on the given SCTPAddr.

func IPAddrFromTCPAddr

func IPAddrFromTCPAddr(addr *TCPAddr) *IPAddr

IPAddrFromTCPAddr returns a new IPAddr based on the given TCPAddr.

func IPAddrFromUDPAddr

func IPAddrFromUDPAddr(addr *UDPAddr) *IPAddr

IPAddrFromUDPAddr returns a new IPAddr based on the given UDPAddr. It sets the IP and Zone fields of the IPAddr with the values from the UDPAddr.

type IPMreq

type IPMreq struct {
	Multiaddr [4]byte // Multicast group address
	Interface [4]byte // Local interface address
}

IPMreq is the IPv4 multicast group request structure. Matches struct ip_mreq in Linux.

type IPMreqn

type IPMreqn struct {
	Multiaddr [4]byte // Multicast group address
	Address   [4]byte // Local interface address
	Ifindex   int32   // Interface index
}

IPMreqn is the IPv4 multicast group request structure with interface index. Matches struct ip_mreqn in Linux.

type IPv6Mreq

type IPv6Mreq struct {
	Multiaddr [16]byte // IPv6 multicast address
	Ifindex   int32    // Interface index
}

IPv6Mreq is the IPv6 multicast group request structure. Matches struct ipv6_mreq in Linux.

type InvalidAddrError

type InvalidAddrError = net.InvalidAddrError

Type aliases for net package compatibility.

type Iovec

type Iovec = zcall.Iovec

Iovec represents a single I/O vector for scatter/gather I/O.

type Linger

type Linger struct {
	Onoff  int32 // Whether linger is enabled
	Linger int32 // Linger time in seconds
}

Linger represents the SO_LINGER socket option value.

type Listener

type Listener = net.Listener

Type aliases for net package compatibility.

type ListenerSocket

type ListenerSocket interface {
	Socket
	Accept() (Socket, error)
}

ListenerSocket accepts incoming connections.

type Msghdr

type Msghdr = zcall.Msghdr

Msghdr represents a message header for sendmsg/recvmsg.

type NetSocket

type NetSocket struct {
	// contains filtered or unexported fields
}

NetSocket represents a network socket with NONBLOCK and CLOEXEC flags.

func NetSocketPair

func NetSocketPair(domain, typ, proto int) ([2]*NetSocket, error)

NetSocketPair creates a pair of connected sockets.

func NewNetSocket

func NewNetSocket(domain, typ, proto int) (*NetSocket, error)

NewNetSocket creates a new socket with the specified domain, type, and protocol.

func NewNetTCPSocket

func NewNetTCPSocket(ipv6 bool) (*NetSocket, error)

NewNetTCPSocket creates a new TCP socket returning the generic *NetSocket type.

func NewNetUDPSocket

func NewNetUDPSocket(ipv6 bool) (*NetSocket, error)

NewNetUDPSocket creates a new UDP socket returning the generic *NetSocket type.

func NewNetUnixSocket

func NewNetUnixSocket(typ int) (*NetSocket, error)

NewNetUnixSocket creates a Unix socket returning the generic *NetSocket type.

func UnixSocketPair

func UnixSocketPair() ([2]*NetSocket, error)

UnixSocketPair creates a pair of connected Unix domain sockets.

func (*NetSocket) Accept

func (s *NetSocket) Accept() (*NetSocket, *RawSockaddrAny, error)

func (*NetSocket) Bind

func (s *NetSocket) Bind(addr Sockaddr) error

func (*NetSocket) Close

func (s *NetSocket) Close() error

func (*NetSocket) Connect

func (s *NetSocket) Connect(addr Sockaddr) error

func (*NetSocket) FD

func (s *NetSocket) FD() *iofd.FD

func (*NetSocket) Listen

func (s *NetSocket) Listen(backlog int) error

func (*NetSocket) NetworkType

func (s *NetSocket) NetworkType() NetworkType

func (*NetSocket) Protocol

func (s *NetSocket) Protocol() UnderlyingProtocol

Protocol returns the socket type (SOCK_STREAM, SOCK_DGRAM, etc.) as UnderlyingProtocol. The socket type is masked to remove flags like SOCK_NONBLOCK and SOCK_CLOEXEC.

func (*NetSocket) Read

func (s *NetSocket) Read(p []byte) (int, error)

func (*NetSocket) Shutdown

func (s *NetSocket) Shutdown(how int) error

func (*NetSocket) Write

func (s *NetSocket) Write(p []byte) (int, error)

type NetworkType

type NetworkType int

NetworkType represents the address family.

const (
	NetworkUnix NetworkType = 1
	NetworkIPv4 NetworkType = 2
	NetworkIPv6 NetworkType = 10
)

type OpError

type OpError = net.OpError

Type aliases for net package compatibility.

type PacketConn

type PacketConn = net.PacketConn

Type aliases for net package compatibility.

type RawSockaddr

type RawSockaddr struct {
	Family uint16
	Data   [14]byte
}

RawSockaddr is the base socket address structure (struct sockaddr).

type RawSockaddrAny

type RawSockaddrAny struct {
	Addr RawSockaddr
	Pad  [112]byte // 128 - sizeof(RawSockaddr) = 128 - 16 = 112
}

RawSockaddrAny is a raw socket address that can hold any address type. Size matches sockaddr_storage (128 bytes).

type RawSockaddrInet4

type RawSockaddrInet4 struct {
	Family uint16
	Port   uint16 // Network byte order (big-endian)
	Addr   [4]byte
	Zero   [8]byte
}

RawSockaddrInet4 is the raw IPv4 socket address (struct sockaddr_in). Size: 16 bytes.

type RawSockaddrInet6

type RawSockaddrInet6 struct {
	Family   uint16
	Port     uint16 // Network byte order (big-endian)
	Flowinfo uint32
	Addr     [16]byte
	ScopeID  uint32
}

RawSockaddrInet6 is the raw IPv6 socket address (struct sockaddr_in6). Size: 28 bytes.

type RawSockaddrUnix

type RawSockaddrUnix struct {
	Family uint16
	Path   [108]byte
}

RawSockaddrUnix is the raw Unix domain socket address (struct sockaddr_un). Size: 110 bytes.

type SCTPAddr

type SCTPAddr struct {
	IP   net.IP
	Port int
	Zone string
}

SCTPAddr represents the address of a SCTP endpoint. It contains the IP address, port number, and IPv6 zone.

func ResolveSCTPAddr

func ResolveSCTPAddr(network, address string) (*SCTPAddr, error)

ResolveSCTPAddr resolves the SCTP network address of the given network and address string. It returns a new SCTPAddr based on the resolved address and network. Possible network values are "sctp", "sctp4", and "sctp6".

func SCTPAddrFromAddrPort

func SCTPAddrFromAddrPort(addr netip.AddrPort) *SCTPAddr

SCTPAddrFromAddrPort returns a new SCTPAddr based on the given netip.AddrPort.

func (*SCTPAddr) Network

func (a *SCTPAddr) Network() string

Network returns the network name "sctp"

func (*SCTPAddr) String

func (a *SCTPAddr) String() string

String returns the string representation of the SCTPAddr. It returns "<nil>" if the SCTPAddr is nil. Otherwise, it combines the IP address, IPv6 zone (if present), and port number using the net.JoinHostPort function and returns the resulting string.

type SCTPConn

type SCTPConn struct {
	*SCTPSocket
	// contains filtered or unexported fields
}

SCTPConn represents an SCTP connection with adaptive I/O support. By default, Read/Write are non-blocking and return iox.ErrWouldBlock immediately. When a deadline is set via SetDeadline/SetReadDeadline/SetWriteDeadline, operations will retry with backoff until success or deadline exceeded.

func DialSCTP

func DialSCTP(network string, laddr, raddr *SCTPAddr) (*SCTPConn, error)

DialSCTP initiates a non-blocking SCTP connection, auto-detecting IPv4/IPv6.

Unlike blocking dialers, this function returns immediately once the connection attempt starts. The SCTP handshake may still be in progress when this function returns (ErrInProgress is silently ignored).

To wait for connection completion, use SCTPDialer with a timeout set.

func DialSCTP4

func DialSCTP4(laddr, raddr *SCTPAddr) (*SCTPConn, error)

DialSCTP4 initiates a non-blocking SCTP connection to an IPv4 address.

Unlike blocking dialers, this function returns immediately once the connection attempt starts. The SCTP handshake may still be in progress when this function returns (ErrInProgress is silently ignored).

To wait for connection completion, use SCTPDialer with a timeout set.

func DialSCTP6

func DialSCTP6(laddr, raddr *SCTPAddr) (*SCTPConn, error)

DialSCTP6 initiates a non-blocking SCTP connection to an IPv6 address.

Unlike blocking dialers, this function returns immediately once the connection attempt starts. The SCTP handshake may still be in progress when this function returns (ErrInProgress is silently ignored).

To wait for connection completion, use SCTPDialer with a timeout set.

func (*SCTPConn) LocalAddr

func (c *SCTPConn) LocalAddr() Addr

LocalAddr returns the local address.

func (*SCTPConn) Read

func (c *SCTPConn) Read(p []byte) (int, error)

Read reads data from the connection with adaptive I/O. If no deadline is set, returns immediately with iox.ErrWouldBlock if not ready. If a deadline is set, retries with backoff until success or deadline exceeded. Returns io.EOF when the connection is closed.

func (*SCTPConn) RemoteAddr

func (c *SCTPConn) RemoteAddr() Addr

RemoteAddr returns the remote address.

func (*SCTPConn) SetDeadline

func (c *SCTPConn) SetDeadline(t time.Time) error

SetDeadline sets both read and write deadlines. A zero value disables the deadline (pure non-blocking mode). When a deadline is set, Read/Write will retry with backoff until success or deadline exceeded (returns ErrTimedOut).

func (*SCTPConn) SetReadDeadline

func (c *SCTPConn) SetReadDeadline(t time.Time) error

SetReadDeadline sets the read deadline. A zero value disables the deadline (pure non-blocking mode).

func (*SCTPConn) SetWriteDeadline

func (c *SCTPConn) SetWriteDeadline(t time.Time) error

SetWriteDeadline sets the write deadline. A zero value disables the deadline (pure non-blocking mode).

func (*SCTPConn) SyscallConn

func (c *SCTPConn) SyscallConn() (syscall.RawConn, error)

SyscallConn returns a raw network connection for direct syscall access. This implements the syscall.Conn interface.

func (*SCTPConn) Write

func (c *SCTPConn) Write(p []byte) (int, error)

Write writes data to the connection with adaptive I/O. If no deadline is set, returns immediately with iox.ErrWouldBlock if not ready. If a deadline is set, retries with backoff until success or deadline exceeded.

type SCTPDialer

type SCTPDialer struct {
	Timeout time.Duration
}

SCTPDialer provides SCTP connection with configurable timeout. By default (zero Timeout), Dial is non-blocking and returns immediately. When Timeout is set, Dial retries with backoff until connected or timeout exceeded.

func (*SCTPDialer) Dial

func (d *SCTPDialer) Dial(network string, laddr, raddr *SCTPAddr) (*SCTPConn, error)

Dial connects to an SCTP address, auto-detecting IPv4/IPv6. If Timeout is zero, returns immediately (non-blocking, may return ErrInProgress). If Timeout is set, retries with backoff until connected or ErrTimedOut.

func (*SCTPDialer) Dial4

func (d *SCTPDialer) Dial4(laddr, raddr *SCTPAddr) (*SCTPConn, error)

Dial4 connects to an IPv4 SCTP address. If Timeout is zero, returns immediately (non-blocking, may return ErrInProgress). If Timeout is set, retries with backoff until connected or ErrTimedOut.

func (*SCTPDialer) Dial6

func (d *SCTPDialer) Dial6(laddr, raddr *SCTPAddr) (*SCTPConn, error)

Dial6 connects to an IPv6 SCTP address. If Timeout is zero, returns immediately (non-blocking, may return ErrInProgress). If Timeout is set, retries with backoff until connected or ErrTimedOut.

func (*SCTPDialer) SetDialTimeout

func (d *SCTPDialer) SetDialTimeout(timeout time.Duration)

SetDialTimeout sets the connection timeout. Zero disables the timeout (pure non-blocking mode).

type SCTPInitMsg

type SCTPInitMsg struct {
	NumOstreams    uint16 // Number of outbound streams
	MaxInstreams   uint16 // Maximum inbound streams
	MaxAttempts    uint16 // Max retransmissions during association setup
	MaxInitTimeout uint16 // Max init timeout (ms)
}

SCTPInitMsg represents SCTP association initialization parameters.

func GetSCTPInitMsg

func GetSCTPInitMsg(fd *iofd.FD) (*SCTPInitMsg, error)

GetSCTPInitMsg gets the SCTP_INITMSG option.

type SCTPListener

type SCTPListener struct {
	*SCTPSocket
	// contains filtered or unexported fields
}

SCTPListener represents an SCTP listener socket with adaptive Accept support. By default, Accept is non-blocking and returns iox.ErrWouldBlock immediately. When a deadline is set via SetDeadline, Accept will retry with backoff until an association arrives or the deadline is exceeded.

func ListenSCTP

func ListenSCTP(network string, laddr *SCTPAddr) (*SCTPListener, error)

ListenSCTP creates an SCTP listener, auto-detecting IPv4/IPv6.

func ListenSCTP4

func ListenSCTP4(laddr *SCTPAddr) (*SCTPListener, error)

ListenSCTP4 creates an SCTP listener on an IPv4 address. Uses SOCK_STREAM (one-to-one) for proper Accept() semantics.

func ListenSCTP6

func ListenSCTP6(laddr *SCTPAddr) (*SCTPListener, error)

ListenSCTP6 creates an SCTP listener on an IPv6 address. Uses SOCK_STREAM (one-to-one) for proper Accept() semantics.

func (*SCTPListener) Accept

func (l *SCTPListener) Accept() (*SCTPConn, error)

Accept accepts an incoming SCTP association with adaptive I/O. If no deadline is set, returns immediately with iox.ErrWouldBlock if no association pending. If a deadline is set, retries with backoff until success or deadline exceeded.

func (*SCTPListener) AcceptSocket

func (l *SCTPListener) AcceptSocket() (Socket, error)

AcceptSocket accepts and returns the underlying Socket interface.

func (*SCTPListener) Addr

func (l *SCTPListener) Addr() Addr

Addr returns the listener's local address.

func (*SCTPListener) SetDeadline

func (l *SCTPListener) SetDeadline(t time.Time) error

SetDeadline sets the deadline for Accept operations. A zero value disables the deadline (pure non-blocking mode).

type SCTPSocket

type SCTPSocket struct {
	*NetSocket
}

SCTPSocket represents an SCTP socket. SCTP provides reliable, message-oriented transport with multi-streaming. Use NewSCTPSocket4/6 for SOCK_SEQPACKET (one-to-many) or NewSCTPStreamSocket4/6 for SOCK_STREAM (one-to-one) semantics.

func NewSCTPSocket4

func NewSCTPSocket4() (*SCTPSocket, error)

NewSCTPSocket4 creates a new IPv4 SCTP socket with SOCK_SEQPACKET (one-to-many).

func NewSCTPSocket6

func NewSCTPSocket6() (*SCTPSocket, error)

NewSCTPSocket6 creates a new IPv6 SCTP socket with SOCK_SEQPACKET (one-to-many).

func NewSCTPStreamSocket4

func NewSCTPStreamSocket4() (*SCTPSocket, error)

NewSCTPStreamSocket4 creates a new IPv4 SCTP socket with SOCK_STREAM (one-to-one).

func NewSCTPStreamSocket6

func NewSCTPStreamSocket6() (*SCTPSocket, error)

NewSCTPStreamSocket6 creates a new IPv6 SCTP socket with SOCK_STREAM (one-to-one).

func (*SCTPSocket) Protocol

func (s *SCTPSocket) Protocol() UnderlyingProtocol

Protocol returns the socket type (SOCK_STREAM or SOCK_SEQPACKET).

type Sockaddr

type Sockaddr interface {
	Raw() (unsafe.Pointer, uint32)
	Family() uint16
}

Sockaddr encodes to raw kernel format without allocation.

func DecodeSockaddr

func DecodeSockaddr(raw *RawSockaddrAny) Sockaddr

DecodeSockaddr decodes a raw sockaddr into a Sockaddr.

func GetPeername

func GetPeername(fd *iofd.FD) (Sockaddr, error)

GetPeername retrieves the remote address of a connected socket.

func GetSockname

func GetSockname(fd *iofd.FD) (Sockaddr, error)

GetSockname retrieves the local address of a socket.

func TCPAddrToSockaddr

func TCPAddrToSockaddr(addr *net.TCPAddr) Sockaddr

TCPAddrToSockaddr converts a *net.TCPAddr to a Sockaddr.

func UDPAddrToSockaddr

func UDPAddrToSockaddr(addr *net.UDPAddr) Sockaddr

UDPAddrToSockaddr converts a *net.UDPAddr to a Sockaddr.

func UnixAddrToSockaddr

func UnixAddrToSockaddr(addr *net.UnixAddr) Sockaddr

UnixAddrToSockaddr converts a *net.UnixAddr to a Sockaddr.

type SockaddrInet4

type SockaddrInet4 struct {
	// contains filtered or unexported fields
}

SockaddrInet4 is a zero-allocation IPv4 socket address.

func NewSockaddrInet4

func NewSockaddrInet4(addr [4]byte, port uint16) *SockaddrInet4

NewSockaddrInet4 creates a new IPv4 socket address.

func (*SockaddrInet4) Addr

func (sa *SockaddrInet4) Addr() [4]byte

func (*SockaddrInet4) Family

func (sa *SockaddrInet4) Family() uint16

func (*SockaddrInet4) Port

func (sa *SockaddrInet4) Port() uint16

func (*SockaddrInet4) Raw

func (sa *SockaddrInet4) Raw() (unsafe.Pointer, uint32)

func (*SockaddrInet4) SetAddr

func (sa *SockaddrInet4) SetAddr(addr [4]byte)

func (*SockaddrInet4) SetPort

func (sa *SockaddrInet4) SetPort(port uint16)

type SockaddrInet6

type SockaddrInet6 struct {
	// contains filtered or unexported fields
}

SockaddrInet6 is a zero-allocation IPv6 socket address.

func NewSockaddrInet6

func NewSockaddrInet6(addr [16]byte, port uint16, zone uint32) *SockaddrInet6

NewSockaddrInet6 creates a new IPv6 socket address.

func (*SockaddrInet6) Addr

func (sa *SockaddrInet6) Addr() [16]byte

func (*SockaddrInet6) Family

func (sa *SockaddrInet6) Family() uint16

func (*SockaddrInet6) Port

func (sa *SockaddrInet6) Port() uint16

func (*SockaddrInet6) Raw

func (sa *SockaddrInet6) Raw() (unsafe.Pointer, uint32)

func (*SockaddrInet6) ScopeID

func (sa *SockaddrInet6) ScopeID() uint32

func (*SockaddrInet6) SetAddr

func (sa *SockaddrInet6) SetAddr(addr [16]byte)

func (*SockaddrInet6) SetPort

func (sa *SockaddrInet6) SetPort(port uint16)

func (*SockaddrInet6) SetScopeID

func (sa *SockaddrInet6) SetScopeID(id uint32)

type SockaddrUnix

type SockaddrUnix struct {
	// contains filtered or unexported fields
}

SockaddrUnix is a zero-allocation Unix domain socket address.

func NewSockaddrUnix

func NewSockaddrUnix(path string) *SockaddrUnix

NewSockaddrUnix creates a new Unix domain socket address.

func (*SockaddrUnix) Family

func (sa *SockaddrUnix) Family() uint16

func (*SockaddrUnix) Path

func (sa *SockaddrUnix) Path() string

func (*SockaddrUnix) Raw

func (sa *SockaddrUnix) Raw() (unsafe.Pointer, uint32)

func (*SockaddrUnix) SetPath

func (sa *SockaddrUnix) SetPath(path string)

type Socket

type Socket interface {
	FD() *iofd.FD
	NetworkType() NetworkType
	Protocol() UnderlyingProtocol
	io.Reader
	io.Writer
	io.Closer
}

Socket is a network socket with handle-based resource management.

type TCPAddr

type TCPAddr = net.TCPAddr

TCPAddr represents the address of a TCP endpoint. It is a type alias for the net.TCPAddr type.

type TCPConn

type TCPConn struct {
	*TCPSocket
	// contains filtered or unexported fields
}

TCPConn represents a TCP connection.

func DialTCP

func DialTCP(network string, laddr, raddr *TCPAddr) (*TCPConn, error)

DialTCP initiates a non-blocking TCP connection, auto-detecting IPv4/IPv6.

Unlike net.Dial, this function returns immediately once the connection attempt starts. The TCP handshake may still be in progress when this function returns (ErrInProgress is silently ignored).

To wait for connection completion, use TCPDialer with a timeout set.

If laddr is nil, the system chooses a local address. Returns ErrInvalidParam if raddr is nil.

func DialTCP4

func DialTCP4(laddr, raddr *TCPAddr) (*TCPConn, error)

DialTCP4 initiates a non-blocking TCP connection to an IPv4 address.

Unlike net.Dial, this function returns immediately once the connection attempt starts. The TCP handshake may still be in progress when this function returns (ErrInProgress is silently ignored).

To wait for connection completion, use TCPDialer with a timeout set.

If laddr is nil, the system chooses a local address. Returns ErrInvalidParam if raddr is nil.

func DialTCP6

func DialTCP6(laddr, raddr *TCPAddr) (*TCPConn, error)

DialTCP6 initiates a non-blocking TCP connection to an IPv6 address.

Unlike net.Dial, this function returns immediately once the connection attempt starts. The TCP handshake may still be in progress when this function returns (ErrInProgress is silently ignored).

To wait for connection completion, use TCPDialer with a timeout set.

If laddr is nil, the system chooses a local address. Returns ErrInvalidParam if raddr is nil.

func (*TCPConn) LocalAddr

func (c *TCPConn) LocalAddr() Addr

func (*TCPConn) Read

func (c *TCPConn) Read(p []byte) (int, error)

func (*TCPConn) RemoteAddr

func (c *TCPConn) RemoteAddr() Addr

func (*TCPConn) SetDeadline

func (c *TCPConn) SetDeadline(t time.Time) error

func (*TCPConn) SetKeepAlive

func (c *TCPConn) SetKeepAlive(keepalive bool) error

func (*TCPConn) SetKeepAlivePeriod

func (c *TCPConn) SetKeepAlivePeriod(d time.Duration) error

func (*TCPConn) SetNoDelay

func (c *TCPConn) SetNoDelay(noDelay bool) error

func (*TCPConn) SetReadDeadline

func (c *TCPConn) SetReadDeadline(t time.Time) error

func (*TCPConn) SetWriteDeadline

func (c *TCPConn) SetWriteDeadline(t time.Time) error

func (*TCPConn) SyscallConn

func (c *TCPConn) SyscallConn() (syscall.RawConn, error)

SyscallConn returns a raw network connection for direct syscall access. This implements the syscall.Conn interface.

func (*TCPConn) Write

func (c *TCPConn) Write(p []byte) (int, error)

type TCPDialer

type TCPDialer struct {
	Timeout time.Duration
}

TCPDialer provides TCP connection with configurable timeout. By default (zero Timeout), Dial is non-blocking and returns immediately. When Timeout is set, Dial retries with backoff until connected or timeout exceeded.

func (*TCPDialer) Dial

func (d *TCPDialer) Dial(network string, laddr, raddr *TCPAddr) (*TCPConn, error)

Dial connects to a TCP address, auto-detecting IPv4/IPv6. If Timeout is zero, returns immediately (non-blocking, may return ErrInProgress). If Timeout is set, retries with backoff until connected or ErrTimedOut.

func (*TCPDialer) Dial4

func (d *TCPDialer) Dial4(laddr, raddr *TCPAddr) (*TCPConn, error)

Dial4 connects to an IPv4 TCP address. If Timeout is zero, returns immediately (non-blocking, may return ErrInProgress). If Timeout is set, retries with backoff until connected or ErrTimedOut.

func (*TCPDialer) Dial6

func (d *TCPDialer) Dial6(laddr, raddr *TCPAddr) (*TCPConn, error)

Dial6 connects to an IPv6 TCP address. If Timeout is zero, returns immediately (non-blocking, may return ErrInProgress). If Timeout is set, retries with backoff until connected or ErrTimedOut.

func (*TCPDialer) SetDialTimeout

func (d *TCPDialer) SetDialTimeout(timeout time.Duration)

SetDialTimeout sets the connection timeout. Zero disables the timeout (pure non-blocking mode).

type TCPInfo

type TCPInfo struct {
	State           uint8 // TCP state (e.g., TCP_ESTABLISHED)
	CAState         uint8 // Congestion avoidance state
	Retransmits     uint8 // Number of retransmits for current SYN/data
	Probes          uint8 // Number of unanswered 0-window probes
	Backoff         uint8 // Backoff timer counter
	Options         uint8 // Bitmask of TCPI_OPT_* flags
	WscaleRcvSnd    uint8 // Packed: snd_wscale:4, rcv_wscale:4
	DeliveryRateApp uint8 // Packed: delivery_rate_app_limited:1, fastopen_client_fail:2

	RTO    uint32 // Retransmit timeout (usec)
	ATO    uint32 // Predicted tick of soft clock (usec)
	SndMss uint32 // Send maximum segment size
	RcvMss uint32 // Receive maximum segment size

	Unacked uint32 // Packets sent but not yet ACKed
	Sacked  uint32 // SACKed packets
	Lost    uint32 // Lost packets
	Retrans uint32 // Retransmitted packets
	Fackets uint32 // FACKed packets

	// Times (msec)
	LastDataSent uint32 // Time since last data sent
	LastAckSent  uint32 // Not remembered, sorry (always 0)
	LastDataRecv uint32 // Time since last data received
	LastAckRecv  uint32 // Time since last ACK received

	// Metrics
	PMTU        uint32 // Path MTU
	RcvSsthresh uint32 // Receive slow start threshold
	RTT         uint32 // Smoothed round trip time (usec)
	RTTVar      uint32 // RTT variance (usec)
	SndSsthresh uint32 // Send slow start threshold
	SndCwnd     uint32 // Send congestion window
	AdvMss      uint32 // Advertised MSS
	Reordering  uint32 // Reordering metric

	RcvRTT   uint32 // Receiver RTT estimate (usec)
	RcvSpace uint32 // Receive buffer space

	TotalRetrans uint32 // Total number of retransmits

	PacingRate    uint64 // Pacing rate (bytes/sec)
	MaxPacingRate uint64 // Max pacing rate (bytes/sec)
	BytesAcked    uint64 // Bytes ACKed (RFC4898)
	BytesReceived uint64 // Bytes received (RFC4898)
	SegsOut       uint32 // Segments sent (RFC4898)
	SegsIn        uint32 // Segments received (RFC4898)

	NotsentBytes uint32 // Bytes not yet sent
	MinRTT       uint32 // Minimum RTT observed (usec)
	DataSegsIn   uint32 // Data segments received (RFC4898)
	DataSegsOut  uint32 // Data segments sent (RFC4898)

	DeliveryRate uint64 // Delivery rate (bytes/sec)

	BusyTime      uint64 // Time busy sending (usec)
	RwndLimited   uint64 // Time limited by receive window (usec)
	SndbufLimited uint64 // Time limited by send buffer (usec)

	Delivered   uint32 // Packets delivered
	DeliveredCE uint32 // Packets delivered with CE mark

	BytesSent    uint64 // Data bytes sent (RFC4898)
	BytesRetrans uint64 // Bytes retransmitted (RFC4898)
	DSACKDups    uint32 // DSACK duplicates
	ReordSeen    uint32 // Reordering events seen

	RcvOoopack uint32 // Out-of-order packets received

	SndWnd uint32 // Peer's receive window after scaling
	RcvWnd uint32 // Local receive window after scaling

	Rehash uint32 // PLB or timeout triggered rehash attempts

	TotalRTO           uint16 // Total RTO timeouts
	TotalRTORecoveries uint16 // Total RTO recoveries
	TotalRTOTime       uint32 // Time in RTO recovery (msec)
	ReceivedCE         uint32 // CE marks received

	// Accurate ECN byte counters (kernel 6.x+)
	DeliveredE1Bytes uint32
	DeliveredE0Bytes uint32
	DeliveredCEBytes uint32
	ReceivedE1Bytes  uint32
	ReceivedE0Bytes  uint32
	ReceivedCEBytes  uint32
	AccECNFailMode   uint16
	AccECNOptSeen    uint16
}

TCPInfo contains detailed information about a TCP connection. This structure matches the Linux kernel's struct tcp_info (uapi/linux/tcp.h). All fields are in host byte order.

func GetTCPInfo

func GetTCPInfo(fd *iofd.FD) (*TCPInfo, error)

GetTCPInfo retrieves TCP connection information. This is a zero-allocation call that reads the kernel's tcp_info structure.

func (*TCPInfo) FastOpenClientFail

func (info *TCPInfo) FastOpenClientFail() uint8

FastOpenClientFail returns the Fast Open client failure code.

func (*TCPInfo) HasECN

func (info *TCPInfo) HasECN() bool

HasECN returns true if ECN was negotiated.

func (*TCPInfo) HasSACK

func (info *TCPInfo) HasSACK() bool

HasSACK returns true if SACK is enabled.

func (*TCPInfo) HasTimestamps

func (info *TCPInfo) HasTimestamps() bool

HasTimestamps returns true if TCP timestamps are enabled.

func (*TCPInfo) HasWscale

func (info *TCPInfo) HasWscale() bool

HasWscale returns true if window scaling is enabled.

func (*TCPInfo) IsDeliveryRateAppLimited

func (info *TCPInfo) IsDeliveryRateAppLimited() bool

IsDeliveryRateAppLimited returns true if delivery rate is application-limited.

func (*TCPInfo) RcvWscale

func (info *TCPInfo) RcvWscale() uint8

RcvWscale returns the receive window scaling factor.

func (*TCPInfo) SndWscale

func (info *TCPInfo) SndWscale() uint8

SndWscale returns the send window scaling factor.

type TCPListener

type TCPListener struct {
	*TCPSocket
	// contains filtered or unexported fields
}

TCPListener represents a TCP listener socket.

func ListenTCP

func ListenTCP(network string, laddr *TCPAddr) (*TCPListener, error)

ListenTCP creates a TCP listener, auto-detecting IPv4/IPv6 based on network and address. Returns ErrInvalidParam if laddr is nil.

func ListenTCP4

func ListenTCP4(laddr *TCPAddr) (*TCPListener, error)

ListenTCP4 creates a TCP listener on an IPv4 address. Returns ErrInvalidParam if laddr is nil.

func ListenTCP6

func ListenTCP6(laddr *TCPAddr) (*TCPListener, error)

ListenTCP6 creates a TCP listener on an IPv6 address. Returns ErrInvalidParam if laddr is nil.

func (*TCPListener) Accept

func (l *TCPListener) Accept() (*TCPConn, error)

func (*TCPListener) AcceptSocket

func (l *TCPListener) AcceptSocket() (Socket, error)

func (*TCPListener) Addr

func (l *TCPListener) Addr() Addr

func (*TCPListener) SetDeadline

func (l *TCPListener) SetDeadline(t time.Time) error

type TCPSocket

type TCPSocket struct {
	*NetSocket
}

TCPSocket represents a TCP socket with SO_REUSEADDR and SO_REUSEPORT.

func NewTCPSocket4

func NewTCPSocket4() (*TCPSocket, error)

NewTCPSocket4 creates a new IPv4 TCP socket with SO_REUSEADDR, SO_REUSEPORT, and SO_ZEROCOPY.

func NewTCPSocket6

func NewTCPSocket6() (*TCPSocket, error)

NewTCPSocket6 creates a new IPv6 TCP socket with SO_REUSEADDR, SO_REUSEPORT, and SO_ZEROCOPY.

func (*TCPSocket) Protocol

func (s *TCPSocket) Protocol() UnderlyingProtocol

type UDPAddr

type UDPAddr = net.UDPAddr

UDPAddr represents the address of a UDP endpoint. It is a type alias for the net.UDPAddr type.

type UDPConn

type UDPConn struct {
	*UDPSocket
	// contains filtered or unexported fields
}

UDPConn represents a UDP connection (connected or unconnected).

func DialUDP

func DialUDP(network string, laddr, raddr *UDPAddr) (*UDPConn, error)

DialUDP creates a connected UDP socket, auto-detecting IPv4/IPv6 based on network and address. Returns ErrInvalidParam if raddr is nil.

func DialUDP4

func DialUDP4(laddr, raddr *UDPAddr) (*UDPConn, error)

DialUDP4 creates a connected IPv4 UDP socket. Returns ErrInvalidParam if raddr is nil.

func DialUDP6

func DialUDP6(laddr, raddr *UDPAddr) (*UDPConn, error)

DialUDP6 creates a connected IPv6 UDP socket. Returns ErrInvalidParam if raddr is nil.

func ListenUDP

func ListenUDP(network string, laddr *UDPAddr) (*UDPConn, error)

ListenUDP creates a bound UDP socket, auto-detecting IPv4/IPv6 based on network and address. Returns ErrInvalidParam if laddr is nil.

func ListenUDP4

func ListenUDP4(laddr *UDPAddr) (*UDPConn, error)

ListenUDP4 creates a bound IPv4 UDP socket. Returns ErrInvalidParam if laddr is nil.

func ListenUDP6

func ListenUDP6(laddr *UDPAddr) (*UDPConn, error)

ListenUDP6 creates a bound IPv6 UDP socket. Returns ErrInvalidParam if laddr is nil.

func (*UDPConn) GetBroadcast

func (c *UDPConn) GetBroadcast() (bool, error)

func (*UDPConn) LocalAddr

func (c *UDPConn) LocalAddr() Addr

func (*UDPConn) Read

func (c *UDPConn) Read(buf []byte) (int, error)

func (*UDPConn) ReadFrom

func (c *UDPConn) ReadFrom(buf []byte) (int, Addr, error)

func (*UDPConn) ReadMsgUDP

func (c *UDPConn) ReadMsgUDP(b, oob []byte) (n, oobn, flags int, addr *UDPAddr, err error)

ReadMsgUDP reads a message from the connection, copying the payload into b and the associated out-of-band data into oob. It returns the number of bytes copied into b, the number of bytes copied into oob, the flags set on the message, and the source address of the message.

This method supports ancillary data (control messages) for advanced use cases such as receiving packet info, timestamps, or other socket options. The packages golang.org/x/net/ipv4 and golang.org/x/net/ipv6 can be used to manipulate IP-level socket options in oob.

By default, this operation is non-blocking and returns iox.ErrWouldBlock if no data is available. When a read deadline is set via SetReadDeadline, the operation retries with backoff until success or deadline exceeded.

func (*UDPConn) RemoteAddr

func (c *UDPConn) RemoteAddr() Addr

func (*UDPConn) SetBroadcast

func (c *UDPConn) SetBroadcast(enable bool) error

func (*UDPConn) SetDeadline

func (c *UDPConn) SetDeadline(t time.Time) error

func (*UDPConn) SetReadDeadline

func (c *UDPConn) SetReadDeadline(t time.Time) error

func (*UDPConn) SetWriteDeadline

func (c *UDPConn) SetWriteDeadline(t time.Time) error

func (*UDPConn) SyscallConn

func (c *UDPConn) SyscallConn() (syscall.RawConn, error)

SyscallConn returns a raw network connection for direct syscall access. This implements the syscall.Conn interface.

func (*UDPConn) Write

func (c *UDPConn) Write(buf []byte) (int, error)

func (*UDPConn) WriteMsgUDP

func (c *UDPConn) WriteMsgUDP(b, oob []byte, addr *UDPAddr) (n, oobn int, err error)

WriteMsgUDP writes a message to addr via c if c isn't connected, or to c's remote address if c is connected (in which case addr must be nil). The payload is copied from b and the associated out-of-band data is copied from oob. It returns the number of payload and out-of-band bytes written.

This method supports ancillary data (control messages) for advanced use cases such as setting packet info, timestamps, or other socket options. The packages golang.org/x/net/ipv4 and golang.org/x/net/ipv6 can be used to manipulate IP-level socket options in oob.

By default, this operation is non-blocking and returns iox.ErrWouldBlock if the socket buffer is full. When a write deadline is set via SetWriteDeadline, the operation retries with backoff until success or deadline exceeded.

func (*UDPConn) WriteTo

func (c *UDPConn) WriteTo(buf []byte, addr Addr) (int, error)

type UDPSocket

type UDPSocket struct {
	*NetSocket
}

UDPSocket represents a UDP socket.

func NewUDPSocket4

func NewUDPSocket4() (*UDPSocket, error)

NewUDPSocket4 creates a new IPv4 UDP socket with SO_REUSEADDR, SO_REUSEPORT, and SO_ZEROCOPY.

func NewUDPSocket6

func NewUDPSocket6() (*UDPSocket, error)

NewUDPSocket6 creates a new IPv6 UDP socket with SO_REUSEADDR, SO_REUSEPORT, and SO_ZEROCOPY.

func (*UDPSocket) Protocol

func (s *UDPSocket) Protocol() UnderlyingProtocol

func (*UDPSocket) RecvFrom

func (s *UDPSocket) RecvFrom(buf []byte) (int, *UDPAddr, error)

func (*UDPSocket) SendTo

func (s *UDPSocket) SendTo(buf []byte, addr *UDPAddr) (int, error)

type Ucred

type Ucred struct {
	Pid uint32 // Process ID
	Uid uint32 // User ID
	Gid uint32 // Group ID
}

Ucred represents Unix credentials passed via SCM_CREDENTIALS.

func ParseUnixCredentials

func ParseUnixCredentials(buf []byte) *Ucred

ParseUnixCredentials extracts credentials from a received control message buffer.

type UnderlyingProtocol

type UnderlyingProtocol int

UnderlyingProtocol represents the socket type / underlying protocol. It corresponds to the SOCK_* constants.

const (
	UnderlyingProtocolStream    UnderlyingProtocol = 1 // SOCK_STREAM - TCP, Unix stream
	UnderlyingProtocolDgram     UnderlyingProtocol = 2 // SOCK_DGRAM - UDP, Unix datagram
	UnderlyingProtocolRaw       UnderlyingProtocol = 3 // SOCK_RAW - Raw sockets
	UnderlyingProtocolSeqPacket UnderlyingProtocol = 5 // SOCK_SEQPACKET - SCTP, Unix seqpacket
)

Socket type constants matching SOCK_* values. These values are consistent across Unix platforms.

type UnixAddr

type UnixAddr = net.UnixAddr

UnixAddr represents a Unix domain socket address.

type UnixConn

type UnixConn struct {
	*UnixSocket
	// contains filtered or unexported fields
}

UnixConn represents a Unix domain socket connection with adaptive I/O. By default, Read/Write/ReadFrom/WriteTo are non-blocking and return iox.ErrWouldBlock. When a deadline is set, operations will retry with backoff until success or timeout.

func DialUnix

func DialUnix(network string, laddr, raddr *UnixAddr) (*UnixConn, error)

DialUnix initiates a non-blocking connection to a Unix domain socket.

Unlike blocking dialers, this function returns immediately once the connection attempt starts. The handshake may still be in progress when this function returns (ErrInProgress is silently ignored).

network must be "unix", "unixgram", or "unixpacket".

func ListenUnixgram

func ListenUnixgram(network string, laddr *UnixAddr) (*UnixConn, error)

ListenUnixgram creates a Unix datagram socket bound to laddr.

func UnixConnPair

func UnixConnPair(network string) ([2]*UnixConn, error)

UnixSocketPair creates a pair of connected Unix domain sockets. network must be "unix" or "unixgram".

func (*UnixConn) LocalAddr

func (c *UnixConn) LocalAddr() Addr

LocalAddr returns the local address.

func (*UnixConn) Read

func (c *UnixConn) Read(p []byte) (int, error)

Read reads data from the connection with adaptive I/O. If no deadline is set, returns immediately with iox.ErrWouldBlock if not ready. For stream sockets (SOCK_STREAM, SOCK_SEQPACKET), returns io.EOF on connection close. For datagram sockets (SOCK_DGRAM), (0, nil) indicates an empty datagram.

func (*UnixConn) ReadFrom

func (c *UnixConn) ReadFrom(buf []byte) (int, Addr, error)

ReadFrom reads a datagram and returns the sender's address with adaptive I/O. For unconnected sockets. If no deadline is set, returns immediately with iox.ErrWouldBlock.

func (*UnixConn) RemoteAddr

func (c *UnixConn) RemoteAddr() Addr

RemoteAddr returns the remote address.

func (*UnixConn) SetDeadline

func (c *UnixConn) SetDeadline(t time.Time) error

SetDeadline sets both read and write deadlines. A zero value disables the deadline (pure non-blocking mode).

func (*UnixConn) SetReadDeadline

func (c *UnixConn) SetReadDeadline(t time.Time) error

SetReadDeadline sets the read deadline. A zero value disables the deadline (pure non-blocking mode).

func (*UnixConn) SetWriteDeadline

func (c *UnixConn) SetWriteDeadline(t time.Time) error

SetWriteDeadline sets the write deadline. A zero value disables the deadline (pure non-blocking mode).

func (*UnixConn) SyscallConn

func (c *UnixConn) SyscallConn() (syscall.RawConn, error)

SyscallConn returns a raw network connection for direct syscall access. This implements the syscall.Conn interface.

func (*UnixConn) Write

func (c *UnixConn) Write(p []byte) (int, error)

Write writes data to the connection with adaptive I/O. If no deadline is set, returns immediately with iox.ErrWouldBlock if not ready.

func (*UnixConn) WriteTo

func (c *UnixConn) WriteTo(buf []byte, addr Addr) (int, error)

WriteTo writes a datagram to the specified address with adaptive I/O. For unconnected sockets. If no deadline is set, returns immediately with iox.ErrWouldBlock.

type UnixListener

type UnixListener struct {
	*UnixSocket
	// contains filtered or unexported fields
}

UnixListener represents a Unix domain socket listener with adaptive Accept support. By default, Accept is non-blocking and returns iox.ErrWouldBlock immediately. When a deadline is set via SetDeadline, Accept will retry with backoff until a connection arrives or the deadline is exceeded.

func ListenUnix

func ListenUnix(network string, laddr *UnixAddr) (*UnixListener, error)

ListenUnix creates a Unix domain socket listener. network must be "unix", "unixgram", or "unixpacket".

func (*UnixListener) Accept

func (l *UnixListener) Accept() (*UnixConn, error)

Accept accepts an incoming connection with adaptive I/O. If no deadline is set, returns immediately with iox.ErrWouldBlock if no connection pending. If a deadline is set, retries with backoff until success or deadline exceeded.

func (*UnixListener) AcceptSocket

func (l *UnixListener) AcceptSocket() (Socket, error)

AcceptSocket accepts and returns the underlying Socket interface.

func (*UnixListener) Addr

func (l *UnixListener) Addr() Addr

Addr returns the listener's local address.

func (*UnixListener) SetDeadline

func (l *UnixListener) SetDeadline(t time.Time) error

SetDeadline sets the deadline for Accept operations. A zero value disables the deadline (pure non-blocking mode).

type UnixSocket

type UnixSocket struct {
	*NetSocket
}

UnixSocket represents a Unix domain socket.

func NewUnixDatagramSocket

func NewUnixDatagramSocket() (*UnixSocket, error)

NewUnixDatagramSocket creates a new Unix datagram socket (SOCK_DGRAM).

func NewUnixSeqpacketSocket

func NewUnixSeqpacketSocket() (*UnixSocket, error)

NewUnixSeqpacketSocket creates a new Unix seqpacket socket (SOCK_SEQPACKET).

func NewUnixStreamSocket

func NewUnixStreamSocket() (*UnixSocket, error)

NewUnixStreamSocket creates a new Unix stream socket (SOCK_STREAM).

func (*UnixSocket) Protocol

func (s *UnixSocket) Protocol() UnderlyingProtocol

Protocol returns the socket protocol.

type UnknownNetworkError

type UnknownNetworkError = net.UnknownNetworkError

Type aliases for net package compatibility.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL