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:
- Strike: Direct syscall execution (non-blocking)
- Spin: Hardware-level synchronization (handled by caller if needed)
- 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 ¶
- TCPSocket, TCPConn, TCPListener for TCP streams
- UDPSocket, UDPConn for UDP datagrams
- [SCTPSocket], [SCTPConn], [SCTPListener] for SCTP (Linux only)
- UnixSocket, UnixConn, UnixListener for Unix domain sockets
- [RawSocket], [RawConn] for raw IP (requires CAP_NET_RAW)
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:
- TCPAddrToSockaddr, SockaddrToTCPAddr
- UDPAddrToSockaddr, SockaddrToUDPAddr
- UnixAddrToSockaddr, SockaddrToUnixAddr
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
- Variables
- func GetIPv6Only(fd *iofd.FD) (bool, error)
- func GetKeepAlive(fd *iofd.FD) (bool, error)
- func GetLinger(fd *iofd.FD) (bool, int, error)
- func GetRecvBuffer(fd *iofd.FD) (int, error)
- func GetReuseAddr(fd *iofd.FD) (bool, error)
- func GetReusePort(fd *iofd.FD) (bool, error)
- func GetSendBuffer(fd *iofd.FD) (int, error)
- func GetSocketError(fd *iofd.FD) error
- func GetSocketType(fd *iofd.FD) (int, error)
- func GetTCPCork(fd *iofd.FD) (bool, error)
- func GetTCPDeferAccept(fd *iofd.FD) (int, error)
- func GetTCPFastOpen(fd *iofd.FD) (int, error)
- func GetTCPKeepCnt(fd *iofd.FD) (int, error)
- func GetTCPKeepIdle(fd *iofd.FD) (int, error)
- func GetTCPKeepIntvl(fd *iofd.FD) (int, error)
- func GetTCPNoDelay(fd *iofd.FD) (bool, error)
- func GetTCPQuickAck(fd *iofd.FD) (bool, error)
- func GetZeroCopy(fd *iofd.FD) (bool, error)
- func IP4AddressToBytes(ip net.IP) [4]byte
- func IP6AddressToBytes(ip net.IP) [16]byte
- func ResolveUnixAddr(network, address string) (*net.UnixAddr, error)
- func SetCloseOnExec(fd *iofd.FD, cloexec bool) error
- func SetIPv6Only(fd *iofd.FD, enable bool) error
- func SetKeepAlive(fd *iofd.FD, enable bool) error
- func SetLinger(fd *iofd.FD, enable bool, secs int) error
- func SetNonBlock(fd *iofd.FD, nonblock bool) error
- func SetRecvBuffer(fd *iofd.FD, size int) error
- func SetReuseAddr(fd *iofd.FD, enable bool) error
- func SetReusePort(fd *iofd.FD, enable bool) error
- func SetSendBuffer(fd *iofd.FD, size int) error
- func SetTCPCork(fd *iofd.FD, enable bool) error
- func SetTCPDeferAccept(fd *iofd.FD, secs int) error
- func SetTCPFastOpen(fd *iofd.FD, qlen int) error
- func SetTCPKeepCnt(fd *iofd.FD, count int) error
- func SetTCPKeepIdle(fd *iofd.FD, secs int) error
- func SetTCPKeepIntvl(fd *iofd.FD, secs int) error
- func SetTCPNoDelay(fd *iofd.FD, enable bool) error
- func SetTCPQuickAck(fd *iofd.FD, enable bool) error
- func SetZeroCopy(fd *iofd.FD, enable bool) error
- func SockaddrToTCPAddr(sa Sockaddr) *net.TCPAddr
- func SockaddrToUDPAddr(sa Sockaddr) *net.UDPAddr
- func SockaddrToUnixAddr(sa Sockaddr, network string) *net.UnixAddr
- type Addr
- type AddrError
- type Conn
- type IP
- type IPAddr
- type InvalidAddrError
- type Linger
- type Listener
- type ListenerSocket
- type NetSocket
- func NetSocketPair(domain, typ, proto int) ([2]*NetSocket, error)
- func NewNetSocket(domain, typ, proto int) (*NetSocket, error)
- func NewNetTCPSocket(ipv6 bool) (*NetSocket, error)
- func NewNetUDPSocket(ipv6 bool) (*NetSocket, error)
- func NewNetUnixSocket(typ int) (*NetSocket, error)
- func UnixSocketPair() ([2]*NetSocket, error)
- func (s *NetSocket) Accept() (*NetSocket, *RawSockaddrAny, error)
- func (s *NetSocket) Bind(addr Sockaddr) error
- func (s *NetSocket) Close() error
- func (s *NetSocket) Connect(addr Sockaddr) error
- func (s *NetSocket) FD() *iofd.FD
- func (s *NetSocket) Listen(backlog int) error
- func (s *NetSocket) NetworkType() NetworkType
- func (s *NetSocket) Protocol() UnderlyingProtocol
- func (s *NetSocket) Read(p []byte) (int, error)
- func (s *NetSocket) Shutdown(how int) error
- func (s *NetSocket) Write(p []byte) (int, error)
- type NetworkType
- type OpError
- type PacketConn
- type RawSockaddr
- type RawSockaddrAny
- type RawSockaddrInet4
- type RawSockaddrInet6
- type RawSockaddrUnix
- type SCTPAddr
- type Sockaddr
- func DecodeSockaddr(raw *RawSockaddrAny) Sockaddr
- func GetPeername(fd *iofd.FD) (Sockaddr, error)
- func GetSockname(fd *iofd.FD) (Sockaddr, error)
- func TCPAddrToSockaddr(addr *net.TCPAddr) Sockaddr
- func UDPAddrToSockaddr(addr *net.UDPAddr) Sockaddr
- func UnixAddrToSockaddr(addr *net.UnixAddr) Sockaddr
- type SockaddrInet4
- type SockaddrInet6
- func (sa *SockaddrInet6) Addr() [16]byte
- func (sa *SockaddrInet6) Family() uint16
- func (sa *SockaddrInet6) Port() uint16
- func (sa *SockaddrInet6) Raw() (unsafe.Pointer, uint32)
- func (sa *SockaddrInet6) ScopeID() uint32
- func (sa *SockaddrInet6) SetAddr(addr [16]byte)
- func (sa *SockaddrInet6) SetPort(port uint16)
- func (sa *SockaddrInet6) SetScopeID(id uint32)
- type SockaddrUnix
- type Socket
- type TCPAddr
- type TCPConn
- func (c *TCPConn) LocalAddr() Addr
- func (c *TCPConn) Read(p []byte) (int, error)
- func (c *TCPConn) RemoteAddr() Addr
- func (c *TCPConn) SetDeadline(t time.Time) error
- func (c *TCPConn) SetKeepAlive(keepalive bool) error
- func (c *TCPConn) SetKeepAlivePeriod(d time.Duration) error
- func (c *TCPConn) SetNoDelay(noDelay bool) error
- func (c *TCPConn) SetReadDeadline(t time.Time) error
- func (c *TCPConn) SetWriteDeadline(t time.Time) error
- func (c *TCPConn) SyscallConn() (syscall.RawConn, error)
- func (c *TCPConn) Write(p []byte) (int, error)
- type TCPDialer
- type TCPListener
- type TCPSocket
- type UDPAddr
- type UDPConn
- func DialUDP(network string, laddr, raddr *UDPAddr) (*UDPConn, error)
- func DialUDP4(laddr, raddr *UDPAddr) (*UDPConn, error)
- func DialUDP6(laddr, raddr *UDPAddr) (*UDPConn, error)
- func ListenUDP(network string, laddr *UDPAddr) (*UDPConn, error)
- func ListenUDP4(laddr *UDPAddr) (*UDPConn, error)
- func ListenUDP6(laddr *UDPAddr) (*UDPConn, error)
- func (c *UDPConn) GetBroadcast() (bool, error)
- func (c *UDPConn) LocalAddr() Addr
- func (c *UDPConn) Read(buf []byte) (int, error)
- func (c *UDPConn) ReadFrom(buf []byte) (int, Addr, error)
- func (c *UDPConn) RemoteAddr() Addr
- func (c *UDPConn) SetBroadcast(enable bool) error
- func (c *UDPConn) SetDeadline(t time.Time) error
- func (c *UDPConn) SetReadDeadline(t time.Time) error
- func (c *UDPConn) SetWriteDeadline(t time.Time) error
- func (c *UDPConn) SyscallConn() (syscall.RawConn, error)
- func (c *UDPConn) Write(buf []byte) (int, error)
- func (c *UDPConn) WriteTo(buf []byte, addr Addr) (int, error)
- type UDPSocket
- type UnderlyingProtocol
- type UnixAddr
- type UnixConn
- func (c *UnixConn) LocalAddr() Addr
- func (c *UnixConn) Read(p []byte) (int, error)
- func (c *UnixConn) ReadFrom(buf []byte) (int, Addr, error)
- func (c *UnixConn) RemoteAddr() Addr
- func (c *UnixConn) SetDeadline(t time.Time) error
- func (c *UnixConn) SetReadDeadline(t time.Time) error
- func (c *UnixConn) SetWriteDeadline(t time.Time) error
- func (c *UnixConn) SyscallConn() (syscall.RawConn, error)
- func (c *UnixConn) Write(p []byte) (int, error)
- func (c *UnixConn) WriteTo(buf []byte, addr Addr) (int, error)
- type UnixListener
- type UnixSocket
- type UnknownNetworkError
Constants ¶
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.
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.
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.
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.
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.
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.
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.
Shutdown constants (SHUT_*) - aliased from zcall for platform compatibility.
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.
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.
const ( IPPROTO_SCTP = 132 IPPROTO_UDPLITE = 136 )
Darwin-specific IPPROTO constants.
const ( SO_DEBUG = 0x0001 SO_DONTROUTE = 0x0010 SO_OOBINLINE = 0x0100 SO_ZEROCOPY = 0 // Not available on Darwin )
Darwin-specific socket options (SO_*).
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_*).
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_*).
const ( POLLIN = 0x0001 POLLPRI = 0x0002 POLLOUT = 0x0004 POLLERR = 0x0008 POLLHUP = 0x0010 POLLNVAL = 0x0020 )
Darwin-specific poll event constants.
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.
const ( SizeofSockaddrInet4 = 16 SizeofSockaddrInet6 = 28 SizeofSockaddrUnix = 106 SizeofSockaddrAny = 128 )
Size constants for socket address structures.
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.
const DefaultBacklog = 511
Default backlog for listen().
const (
IPV6_V6ONLY = 27
)
Darwin-specific IPv6 options (IPV6_*).
const SYS_FCNTL = 92
SYS_FCNTL is the syscall number for fcntl. Darwin: 92, FreeBSD: 92
const (
TCP_KEEPALIVE = 0x10 // Darwin's equivalent of TCP_KEEPIDLE
)
Darwin-specific socket option constants
Variables ¶
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
}
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 )
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 )
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 )
var ( ErrInvalidParam = iofd.ErrInvalidParam ErrInterrupted = iofd.ErrInterrupted ErrNoMemory = iofd.ErrNoMemory ErrPermission = iofd.ErrPermission )
Common errors reused from iofd for semantic consistency.
var ( ErrInProgress = errors.New("sock: operation in progress") ErrNotSupported = errors.New("sock: operation not supported") )
Socket-specific errors.
var ( DefaultResolver = net.DefaultResolver NetworkByteOrder = binary.BigEndian )
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 ¶
GetIPv6Only returns the current IPV6_V6ONLY setting.
func GetKeepAlive ¶
GetKeepAlive returns the current SO_KEEPALIVE setting.
func GetLinger ¶
GetLinger returns the current SO_LINGER setting. Returns (enabled, seconds, error).
func GetRecvBuffer ¶
GetRecvBuffer returns the current SO_RCVBUF setting.
func GetReuseAddr ¶
GetReuseAddr returns the current SO_REUSEADDR setting.
func GetReusePort ¶
GetReusePort returns the current SO_REUSEPORT setting.
func GetSendBuffer ¶
GetSendBuffer returns the current SO_SNDBUF setting.
func GetSocketError ¶
GetSocketError retrieves and clears the pending socket error.
func GetSocketType ¶
GetSocketType returns the socket type (SOCK_STREAM, SOCK_DGRAM, etc.).
func GetTCPDeferAccept ¶
GetTCPDeferAccept is not available on Darwin.
func GetTCPFastOpen ¶
GetTCPFastOpen is not available on Darwin.
func GetTCPKeepCnt ¶
GetTCPKeepCnt returns the current TCP_KEEPCNT setting.
func GetTCPKeepIdle ¶
GetTCPKeepIdle gets the TCP keepalive idle time on Darwin.
func GetTCPKeepIntvl ¶
GetTCPKeepIntvl returns the current TCP_KEEPINTVL setting.
func GetTCPNoDelay ¶
GetTCPNoDelay returns the current TCP_NODELAY setting.
func GetTCPQuickAck ¶
GetTCPQuickAck is not available on Darwin.
func GetZeroCopy ¶
GetZeroCopy is not available on Darwin.
func IP4AddressToBytes ¶
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 ¶
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 ¶
ResolveUnixAddr returns an address of Unix domain socket. The network must be "unix", "unixgram", or "unixpacket".
func SetCloseOnExec ¶
SetCloseOnExec sets the FD_CLOEXEC flag on the file descriptor.
func SetIPv6Only ¶
SetIPv6Only enables or disables the IPV6_V6ONLY socket option.
func SetKeepAlive ¶
SetKeepAlive enables or disables the SO_KEEPALIVE socket option. When enabled, the socket sends keepalive probes to detect dead peers.
func SetLinger ¶
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 ¶
SetNonBlock sets the O_NONBLOCK flag on the file descriptor.
func SetRecvBuffer ¶
SetRecvBuffer sets the SO_RCVBUF socket option. This sets the receive buffer size in bytes.
func SetReuseAddr ¶
SetReuseAddr enables or disables the SO_REUSEADDR socket option. When enabled, allows binding to an address that is already in use.
func SetReusePort ¶
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 ¶
SetSendBuffer sets the SO_SNDBUF socket option. This sets the send buffer size in bytes.
func SetTCPCork ¶
SetTCPCork is not available on Darwin.
func SetTCPDeferAccept ¶
SetTCPDeferAccept is not available on Darwin.
func SetTCPFastOpen ¶
SetTCPFastOpen is not available on Darwin in the same way as Linux.
func SetTCPKeepCnt ¶
SetTCPKeepCnt sets the TCP_KEEPCNT socket option. This sets the maximum number of keepalive probes before dropping the connection.
func SetTCPKeepIdle ¶
SetTCPKeepIdle sets the TCP keepalive idle time on Darwin. On Darwin, this is TCP_KEEPALIVE instead of TCP_KEEPIDLE.
func SetTCPKeepIntvl ¶
SetTCPKeepIntvl sets the TCP_KEEPINTVL socket option. This sets the time (in seconds) between individual keepalive probes.
func SetTCPNoDelay ¶
SetTCPNoDelay enables or disables the TCP_NODELAY socket option. When enabled, disables Nagle's algorithm for lower latency.
func SetTCPQuickAck ¶
SetTCPQuickAck is not available on Darwin.
func SetZeroCopy ¶
SetZeroCopy is not available on Darwin.
func SockaddrToTCPAddr ¶
SockaddrToTCPAddr converts a Sockaddr to a *net.TCPAddr.
func SockaddrToUDPAddr ¶
SockaddrToUDPAddr converts a Sockaddr to a *net.UDPAddr.
Types ¶
type IPAddr ¶
IPAddr represents a network address of type IP. It is a type alias for the net.IPAddr type.
func IPAddrFromSCTPAddr ¶
IPAddrFromSCTPAddr returns a new IPAddr based on the given SCTPAddr.
func IPAddrFromTCPAddr ¶
IPAddrFromTCPAddr returns a new IPAddr based on the given TCPAddr.
func IPAddrFromUDPAddr ¶
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 ListenerSocket ¶
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 ¶
NetSocketPair creates a pair of connected sockets.
func NewNetSocket ¶
NewNetSocket creates a new socket with the specified domain, type, and protocol.
func NewNetTCPSocket ¶
NewNetTCPSocket creates a new TCP socket returning the generic *NetSocket type.
func NewNetUDPSocket ¶
NewNetUDPSocket creates a new UDP socket returning the generic *NetSocket type.
func NewNetUnixSocket ¶
NewNetUnixSocket creates a Unix socket returning the generic *NetSocket type.
func UnixSocketPair ¶
UnixSocketPair creates a pair of connected Unix domain sockets.
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.
type NetworkType ¶
type NetworkType int
NetworkType represents the address family.
const ( NetworkUnix NetworkType = 1 NetworkIPv4 NetworkType = 2 NetworkIPv6 NetworkType = 10 )
type RawSockaddr ¶
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 ¶
RawSockaddrUnix is the raw Unix domain socket address (struct sockaddr_un). Size: 106 bytes on BSD/Darwin (shorter path than Linux).
type SCTPAddr ¶
SCTPAddr represents the address of a SCTP endpoint. It contains the IP address, port number, and IPv6 zone.
func ResolveSCTPAddr ¶
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 ¶
SCTPAddrFromAddrPort returns a new SCTPAddr based on the given netip.AddrPort.
type Sockaddr ¶
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 ¶
GetPeername retrieves the remote address of a connected socket.
func GetSockname ¶
GetSockname retrieves the local address of a socket.
func TCPAddrToSockaddr ¶
TCPAddrToSockaddr converts a *net.TCPAddr to a Sockaddr.
func UDPAddrToSockaddr ¶
UDPAddrToSockaddr converts a *net.UDPAddr to a Sockaddr.
func UnixAddrToSockaddr ¶
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) 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) 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) 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 ¶
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 ¶
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 ¶
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 ¶
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) RemoteAddr ¶
func (*TCPConn) SetKeepAlive ¶
func (*TCPConn) SetNoDelay ¶
func (*TCPConn) SyscallConn ¶
SyscallConn returns a raw network connection for direct syscall access. This implements the syscall.Conn interface.
type TCPDialer ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
NewTCPSocket4 creates a new IPv4 TCP socket with SO_REUSEADDR, SO_REUSEPORT, and SO_ZEROCOPY.
func NewTCPSocket6 ¶
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 ¶
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 ¶
DialUDP creates a connected UDP socket, auto-detecting IPv4/IPv6 based on network and address. Returns ErrInvalidParam if raddr is nil.
func DialUDP4 ¶
DialUDP4 creates a connected IPv4 UDP socket. Returns ErrInvalidParam if raddr is nil.
func DialUDP6 ¶
DialUDP6 creates a connected IPv6 UDP socket. Returns ErrInvalidParam if raddr is nil.
func ListenUDP ¶
ListenUDP creates a bound UDP socket, auto-detecting IPv4/IPv6 based on network and address. Returns ErrInvalidParam if laddr is nil.
func ListenUDP4 ¶
ListenUDP4 creates a bound IPv4 UDP socket. Returns ErrInvalidParam if laddr is nil.
func ListenUDP6 ¶
ListenUDP6 creates a bound IPv6 UDP socket. Returns ErrInvalidParam if laddr is nil.
func (*UDPConn) GetBroadcast ¶
func (*UDPConn) RemoteAddr ¶
func (*UDPConn) SetBroadcast ¶
func (*UDPConn) SyscallConn ¶
SyscallConn returns a raw network connection for direct syscall access. This implements the syscall.Conn interface.
type UDPSocket ¶
type UDPSocket struct {
*NetSocket
}
UDPSocket represents a UDP socket.
func NewUDPSocket4 ¶
NewUDPSocket4 creates a new IPv4 UDP socket with SO_REUSEADDR, SO_REUSEPORT, and SO_ZEROCOPY.
func NewUDPSocket6 ¶
NewUDPSocket6 creates a new IPv6 UDP socket with SO_REUSEADDR, SO_REUSEPORT, and SO_ZEROCOPY.
func (*UDPSocket) Protocol ¶
func (s *UDPSocket) Protocol() UnderlyingProtocol
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 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 ¶
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 ¶
ListenUnixgram creates a Unix datagram socket bound to laddr.
func UnixConnPair ¶
UnixSocketPair creates a pair of connected Unix domain sockets. network must be "unix" or "unixgram".
func (*UnixConn) Read ¶
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 ¶
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 ¶
RemoteAddr returns the remote address.
func (*UnixConn) SetDeadline ¶
SetDeadline sets both read and write deadlines. A zero value disables the deadline (pure non-blocking mode).
func (*UnixConn) SetReadDeadline ¶
SetReadDeadline sets the read deadline. A zero value disables the deadline (pure non-blocking mode).
func (*UnixConn) SetWriteDeadline ¶
SetWriteDeadline sets the write deadline. A zero value disables the deadline (pure non-blocking mode).
func (*UnixConn) SyscallConn ¶
SyscallConn returns a raw network connection for direct syscall access. This implements the syscall.Conn interface.
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.