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: 1

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 constants for BSD/Darwin. These values are consistent across FreeBSD and Darwin.

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    = 132
	IPPROTO_UDPLITE = 136
)

Darwin-specific IPPROTO constants.

View Source
const (
	SO_DEBUG     = 0x0001
	SO_DONTROUTE = 0x0010
	SO_OOBINLINE = 0x0100
	SO_ZEROCOPY  = 0 // Not available on Darwin
)

Darwin-specific socket options (SO_*).

View Source
const (
	TCP_MAXSEG        = 0x02
	TCP_CORK          = 0    // Not available on Darwin
	TCP_KEEPIDLE      = 0x10 // TCP_KEEPALIVE on Darwin
	TCP_SYNCNT        = 0    // Not available on Darwin
	TCP_LINGER2       = 0    // Not available on Darwin
	TCP_DEFER_ACCEPT  = 0    // Not available on Darwin
	TCP_WINDOW_CLAMP  = 0    // Not available on Darwin
	TCP_QUICKACK      = 0    // Not available on Darwin
	TCP_CONGESTION    = 0    // Not available on Darwin
	TCP_FASTOPEN      = 0    // Not available on Darwin
	TCP_NOTSENT_LOWAT = 0x201
)

Darwin-specific TCP options (TCP_*).

View Source
const (
	MSG_CTRUNC       = 0x20
	MSG_EOR          = 0x8
	MSG_NOSIGNAL     = 0x80000 // Not directly available, use SO_NOSIGPIPE
	MSG_MORE         = 0       // Not available on Darwin
	MSG_WAITFORONE   = 0       // Not available on Darwin
	MSG_FASTOPEN     = 0       // Not available on Darwin
	MSG_CMSG_CLOEXEC = 0       // Not available on Darwin
	MSG_ZEROCOPY     = 0       // Not available on Darwin
)

Darwin-specific message flags (MSG_*).

View Source
const (
	POLLIN   = 0x0001
	POLLPRI  = 0x0002
	POLLOUT  = 0x0004
	POLLERR  = 0x0008
	POLLHUP  = 0x0010
	POLLNVAL = 0x0020
)

Darwin-specific poll event constants.

View Source
const (
	O_CREAT  = 0x0200
	O_EXCL   = 0x0800
	O_NOCTTY = 0x20000
	O_TRUNC  = 0x0400
	O_APPEND = 0x0008
	O_SYNC   = 0x0080
	O_DIRECT = 0 // Not available on Darwin
)

Darwin-specific file descriptor flags.

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

Size constants for socket address structures.

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

Address family constants - aliases to zcall for convenience.

View Source
const DefaultBacklog = 511

Default backlog for listen().

View Source
const (
	IPV6_V6ONLY = 27
)

Darwin-specific IPv6 options (IPV6_*).

View Source
const SYS_FCNTL = 92

SYS_FCNTL is the syscall number for fcntl. Darwin: 92, FreeBSD: 92

View Source
const (
	TCP_KEEPALIVE = 0x10 // Darwin's equivalent of TCP_KEEPIDLE
)

Darwin-specific socket option constants

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 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 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 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 is not available on Darwin.

func GetTCPDeferAccept

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

GetTCPDeferAccept is not available on Darwin.

func GetTCPFastOpen

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

GetTCPFastOpen is not available on Darwin.

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 gets the TCP keepalive idle time on Darwin.

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 is not available on Darwin.

func GetZeroCopy

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

GetZeroCopy is not available on Darwin.

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 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 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.

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 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 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 is not available on Darwin.

func SetTCPDeferAccept

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

SetTCPDeferAccept is not available on Darwin.

func SetTCPFastOpen

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

SetTCPFastOpen is not available on Darwin in the same way as Linux.

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 keepalive idle time on Darwin. On Darwin, this is TCP_KEEPALIVE instead of TCP_KEEPIDLE.

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 is not available on Darwin.

func SetZeroCopy

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

SetZeroCopy is not available on Darwin.

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.

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 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 InvalidAddrError

type InvalidAddrError = net.InvalidAddrError

Type aliases for net package compatibility.

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 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 {
	Len    uint8
	Family uint8
	Data   [14]byte
}

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

type RawSockaddrAny

type RawSockaddrAny struct {
	Addr RawSockaddr
	Pad  [112]byte
}

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

type RawSockaddrInet4

type RawSockaddrInet4 struct {
	Len    uint8
	Family uint8
	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 {
	Len      uint8
	Family   uint8
	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 {
	Len    uint8
	Family uint8
	Path   [104]byte
}

RawSockaddrUnix is the raw Unix domain socket address (struct sockaddr_un). Size: 106 bytes on BSD/Darwin (shorter path than Linux).

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 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 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) 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) 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 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