Documentation
¶
Overview ¶
Package net provides basic TCP, UDP, and Unix domain socket networking.
It is a small subset of Go's net package. TCP (networks "tcp", "tcp4", "tcp6"), UDP (networks "udp", "udp4", "udp6"), and Unix domain sockets ("unix" for streams and "unixgram" for datagrams) are supported; there is no concurrent server support.
TCP is served by ResolveTCPAddr, DialTCP and ListenTCP functions, and the associated TCPConn and TCPListener types.
UDP is served by ResolveUDPAddr, DialUDP (a connected socket, with UDPConn.Read/UDPConn.Write) and ListenUDP (an unconnected socket, with UDPConn.ReadFrom/UDPConn.WriteTo).
Unix domain sockets are served by ResolveUnixAddr, DialUnix, ListenUnix (stream), and ListenUnixgram (datagram), sharing the UnixConn type; a ListenUnix or ListenUnixgram socket file is removed on Close.
Accept, Read, and Write block by default. They can be bounded with a deadline: TCPConn.SetDeadline, TCPListener.SetDeadline, UDPConn.SetDeadline, UnixConn.SetDeadline and UnixListener.SetDeadline make a pending call fail with ErrTimeout once the deadline passes. Without a deadline, a blocked call waits indefinitely.
Index ¶
- Variables
- func JoinHostPort(buf []byte, host, port string) string
- type HostPort
- type TCPAddr
- type TCPConn
- func (conn *TCPConn) Close() error
- func (conn *TCPConn) LocalAddr() TCPAddr
- func (conn *TCPConn) Read(b []byte) (int, error)
- func (conn *TCPConn) RemoteAddr() TCPAddr
- func (conn *TCPConn) SetDeadline(t time.Time) error
- func (conn *TCPConn) SetReadDeadline(t time.Time) error
- func (conn *TCPConn) SetWriteDeadline(t time.Time) error
- func (conn *TCPConn) Write(b []byte) (int, error)
- type TCPListener
- type UDPAddr
- type UDPConn
- func (conn *UDPConn) Close() error
- func (conn *UDPConn) LocalAddr() UDPAddr
- func (conn *UDPConn) Read(b []byte) (int, error)
- func (conn *UDPConn) ReadFrom(b []byte) (UDPRead, error)
- func (conn *UDPConn) RemoteAddr() UDPAddr
- func (conn *UDPConn) SetDeadline(t time.Time) error
- func (conn *UDPConn) SetReadDeadline(t time.Time) error
- func (conn *UDPConn) SetWriteDeadline(t time.Time) error
- func (conn *UDPConn) Write(b []byte) (int, error)
- func (conn *UDPConn) WriteTo(b []byte, addr *UDPAddr) (int, error)
- type UDPRead
- type UnixAddr
- type UnixConn
- func (conn *UnixConn) Close() error
- func (conn *UnixConn) LocalAddr() UnixAddr
- func (conn *UnixConn) Read(b []byte) (int, error)
- func (conn *UnixConn) ReadFrom(b []byte) (UnixRead, error)
- func (conn *UnixConn) RemoteAddr() UnixAddr
- func (conn *UnixConn) SetDeadline(t time.Time) error
- func (conn *UnixConn) SetReadDeadline(t time.Time) error
- func (conn *UnixConn) SetWriteDeadline(t time.Time) error
- func (conn *UnixConn) Write(b []byte) (int, error)
- func (conn *UnixConn) WriteTo(b []byte, addr *UnixAddr) (int, error)
- type UnixListener
- type UnixRead
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var ( // ErrAddrInUse indicates the local address is already in use. ErrAddrInUse = errors.New("net: address already in use") // ErrAddrNotAvail indicates the requested address is not available. ErrAddrNotAvail = errors.New("net: cannot assign requested address") // ErrBrokenPipe indicates a write to a connection whose peer has // already closed its end (the local send saw EPIPE). ErrBrokenPipe = errors.New("net: broken pipe") // ErrClosed is returned by I/O methods on a connection or listener // that has already been closed. ErrClosed = errors.New("net: use of closed network connection") // ErrConnAborted indicates the connection was aborted locally. ErrConnAborted = errors.New("net: connection aborted") // ErrConnRefused indicates the remote host refused the connection. ErrConnRefused = errors.New("net: connection refused") // ErrConnReset indicates the connection was reset by the peer. ErrConnReset = errors.New("net: connection reset by peer") // ErrInvalidPort indicates the port is not a valid number in 0..65535. ErrInvalidPort = errors.New("net: invalid port") // ErrMissingBracket indicates an IPv6 literal is missing its closing ']'. ErrMissingBracket = errors.New("net: missing ']' in address") // ErrMissingPort indicates an address is missing the port. ErrMissingPort = errors.New("net: missing port in address") // ErrMsgTooLong indicates a datagram was larger // than the maximum allowed size. ErrMsgTooLong = errors.New("net: message too long") // ErrNoSuchHost indicates the host could not be resolved. ErrNoSuchHost = errors.New("net: no such host") // ErrNoSuitableAddr indicates the address does not match the network's // family, for example an IPv6 literal with the "tcp4" network. ErrNoSuitableAddr = errors.New("net: no suitable address found") // ErrTimeout indicates the operation timed out. ErrTimeout = errors.New("net: operation timed out") // ErrTooManyColons indicates an unbracketed address has too many colons. ErrTooManyColons = errors.New("net: too many colons in address") // ErrUnexpectedBracket indicates an unexpected bracket in the address. ErrUnexpectedBracket = errors.New("net: unexpected '[' or ']' in address") // ErrUnknownNetwork is returned when the network argument is not one of // "tcp", "tcp4", or "tcp6". ErrUnknownNetwork = errors.New("net: unknown network") // ErrUnreachable indicates the network or host is unreachable. ErrUnreachable = errors.New("net: network or host is unreachable") // ErrIO is a generic network error returned when the cause does not // match any of the other, more specific errors. ErrIO = errors.New("net: i/o error") )
Errors that can be returned by functions in this package.
Functions ¶
func JoinHostPort ¶
JoinHostPort combines host and port into a network address of the form "host:port". If host contains a colon, as found in literal IPv6 addresses, then JoinHostPort returns "[host]:port".
The result is built into buf and aliases it, so buf must have enough capacity (len(host)+len(port)+4 is always sufficient).
Types ¶
type HostPort ¶
HostPort holds the host and port parts of an address.
func SplitHostPort ¶
SplitHostPort splits a network address of the form "host:port", "host%zone:port", "[host]:port" or "[host%zone]:port" into host or host%zone and port.
The returned strings are views into hostport.
type TCPAddr ¶
TCPAddr represents the address of a TCP endpoint.
func ResolveTCPAddr ¶
ResolveTCPAddr returns the address of a TCP endpoint.
Known networks are "tcp", "tcp4" (IPv4-only), and "tcp6" (IPv6-only).
The address has the form "host:port". An empty host means the unspecified address (0.0.0.0 or ::). An IP literal host is parsed directly; otherwise it is resolved via the system resolver, and a host name with several addresses resolves to its first. The port may be a decimal number or a service name (for example "http").
Examples:
ResolveTCPAddr("tcp", "golang.org:443")
ResolveTCPAddr("tcp", "192.0.2.1:80")
ResolveTCPAddr("tcp", "localhost:http")
ResolveTCPAddr("tcp", ":80")
type TCPConn ¶
type TCPConn struct {
// contains filtered or unexported fields
}
TCPConn abstracts a TCP network connection.
The zero value is not usable; obtain a TCPConn from DialTCP or TCPListener.Accept. A TCPConn must not be copied after use (copies share the underlying socket descriptor).
func DialTCP ¶
DialTCP connects to raddr on the named TCP network.
Known networks are "tcp", "tcp4" (IPv4-only), and "tcp6" (IPv6-only). Use ResolveTCPAddr to obtain raddr (and an optional laddr) from a "host:port" string.
If laddr is nil, a local address is automatically chosen. A laddr with an invalid IP binds only its port, on the unspecified address of the remote's family.
Example ¶
Connect to a TCP server, send a request, and read the reply.
package main
import (
"solod.dev/so/net"
)
func main() {
// Resolve the server address. An IP literal needs no DNS lookup.
raddr, err := net.ResolveTCPAddr("tcp", "127.0.0.1:8080")
if err != nil {
panic(err)
}
// Connect. A nil laddr lets the system choose the local address.
conn, err := net.DialTCP("tcp", nil, &raddr)
if err != nil {
panic(err)
}
defer conn.Close()
// Send a request.
if _, err := conn.Write([]byte("ping")); err != nil {
panic(err)
}
// Read the reply.
var buf [256]byte
n, err := conn.Read(buf[:])
if err != nil {
panic(err)
}
println(string(buf[:n]))
}
Output:
func (*TCPConn) Close ¶
Close closes the connection. Returns an error if it has already been called.
func (*TCPConn) Read ¶
Read reads data from the connection into b. At end of stream, Read returns 0, io.EOF.
func (*TCPConn) RemoteAddr ¶
RemoteAddr returns the remote network address.
func (*TCPConn) SetDeadline ¶
SetDeadline sets the read and write deadlines associated with the connection. It is equivalent to calling both SetReadDeadline and SetWriteDeadline.
A deadline is an absolute time after which I/O operations fail instead of blocking. The deadline applies to all future I/O, not just the immediately following call to Read or Write. After a deadline has been exceeded, the connection can be refreshed by setting a deadline in the future.
If the deadline is exceeded a call to Read or Write or to other I/O methods will return ErrTimeout.
An idle timeout can be implemented by repeatedly extending the deadline after successful Read or Write calls.
A zero value for t means I/O operations will not time out.
func (*TCPConn) SetReadDeadline ¶
SetReadDeadline sets the deadline for future Read calls. A zero value for t means Read will not time out.
func (*TCPConn) SetWriteDeadline ¶
SetWriteDeadline sets the deadline for future Write calls. A zero value for t means Write will not time out.
type TCPListener ¶
type TCPListener struct {
// contains filtered or unexported fields
}
TCPListener is a TCP network listener. The zero value is not usable; obtain one from ListenTCP.
func ListenTCP ¶
func ListenTCP(network string, laddr *TCPAddr) (TCPListener, error)
ListenTCP announces on the local TCP address laddr.
Known networks are "tcp", "tcp4" (IPv4-only), and "tcp6" (IPv6-only). Use ResolveTCPAddr to obtain laddr from a "host:port" string.
A nil laddr, or an unspecified IP in laddr (0.0.0.0 or ::, as produced by an empty host), listens on all interfaces of the network's address family: 0.0.0.0 (all IPv4 interfaces) for "tcp" or "tcp4", :: (all IPv6 interfaces) for "tcp6". A zero Port lets the system pick a free port, which the returned listener's TCPListener.Addr reports.
Example ¶
Announce on a local TCP address and serve connections one at a time, echoing back whatever each client sends. This package has no goroutines, so connections are handled sequentially.
package main
import (
"solod.dev/so/net"
)
func main() {
// Resolve the local address to listen on (IP literal, no DNS).
laddr, err := net.ResolveTCPAddr("tcp", "127.0.0.1:8080")
if err != nil {
panic(err)
}
ln, err := net.ListenTCP("tcp", &laddr)
if err != nil {
panic(err)
}
defer ln.Close()
for {
conn, err := ln.Accept()
if err != nil {
panic(err)
}
// Echo one message back to the client, then close the connection.
var buf [256]byte
n, err := conn.Read(buf[:])
if err == nil {
conn.Write(buf[:n])
}
conn.Close()
}
}
Output:
func (*TCPListener) Accept ¶
func (l *TCPListener) Accept() (TCPConn, error)
Accept waits for and returns the next connection to the listener.
func (*TCPListener) Addr ¶
func (l *TCPListener) Addr() TCPAddr
Addr returns the listener's network address.
func (*TCPListener) Close ¶
func (l *TCPListener) Close() error
Close stops listening on the TCP address. Already accepted connections are not closed.
func (*TCPListener) SetDeadline ¶
func (l *TCPListener) SetDeadline(t time.Time) error
SetDeadline sets the deadline for future Accept calls. An Accept that has no connection ready before t fails with ErrTimeout. The zero value for t clears the deadline (Accept blocks until a connection arrives).
type UDPAddr ¶
UDPAddr represents the address of a UDP endpoint.
func ResolveUDPAddr ¶
ResolveUDPAddr returns the address of a UDP endpoint.
Known networks are "udp", "udp4" (IPv4-only), and "udp6" (IPv6-only).
The address has the form "host:port". An empty host means the unspecified address (0.0.0.0 or ::). An IP literal host is parsed directly; otherwise it is resolved via the system resolver, and a host name with several addresses resolves to its first. The port may be a decimal number or a service name (for example "domain").
Examples:
ResolveUDPAddr("udp", "golang.org:53")
ResolveUDPAddr("udp", "192.0.2.1:53")
ResolveUDPAddr("udp", "localhost:domain")
ResolveUDPAddr("udp", ":53")
type UDPConn ¶
type UDPConn struct {
// contains filtered or unexported fields
}
UDPConn is a UDP network connection. It is used both for connected sockets (from DialUDP, which fix a peer and support UDPConn.Read/UDPConn.Write) and for unconnected sockets (from ListenUDP, which exchange datagrams with arbitrary peers via UDPConn.ReadFrom/UDPConn.WriteTo).
The zero value is not usable. A UDPConn must not be copied after use (copies share the underlying socket descriptor).
func DialUDP ¶
DialUDP creates a connected UDP socket bound to a fixed peer raddr, on the named UDP network.
Known networks are "udp", "udp4" (IPv4-only), and "udp6" (IPv6-only). Use ResolveUDPAddr to obtain raddr (and an optional laddr) from a "host:port" string.
A connected socket sends every datagram to raddr and only accepts datagrams from it; use UDPConn.Read and UDPConn.Write. If laddr is nil, a local address is automatically chosen. A laddr with an invalid IP binds only its port, on the unspecified address of the remote's family.
Example ¶
Connect a UDP socket to a server, send a datagram, and read the reply.
package main
import (
"solod.dev/so/net"
)
func main() {
// Resolve the server address. An IP literal needs no DNS lookup.
raddr, err := net.ResolveUDPAddr("udp", "127.0.0.1:8080")
if err != nil {
panic(err)
}
// Connect: fixes the peer so Read/Write can be used. A nil laddr lets the
// system choose the local address.
conn, err := net.DialUDP("udp", nil, &raddr)
if err != nil {
panic(err)
}
defer conn.Close()
// Send one datagram.
if _, err := conn.Write([]byte("ping")); err != nil {
panic(err)
}
// Read the reply datagram.
var buf [256]byte
n, err := conn.Read(buf[:])
if err != nil {
panic(err)
}
println(string(buf[:n]))
}
Output:
func ListenUDP ¶
ListenUDP creates an unconnected UDP socket bound to the local address laddr.
Known networks are "udp", "udp4" (IPv4-only), and "udp6" (IPv6-only). Use ResolveUDPAddr to obtain laddr from a "host:port" string.
A nil laddr, or an unspecified IP in laddr (0.0.0.0 or ::, as produced by an empty host), binds all interfaces of the network's address family. A zero Port lets the system pick a free port, which the returned connection's UDPConn.LocalAddr reports. The socket is unconnected: exchange datagrams with arbitrary peers via UDPConn.ReadFrom and UDPConn.WriteTo.
Example ¶
Listen on a local UDP address and echo each datagram back to its sender. An unconnected socket talks to many peers, so ReadFrom reports the source address and WriteTo replies to it.
package main
import (
"solod.dev/so/net"
)
func main() {
// Resolve the local address to listen on (IP literal, no DNS).
laddr, err := net.ResolveUDPAddr("udp", "127.0.0.1:8080")
if err != nil {
panic(err)
}
conn, err := net.ListenUDP("udp", &laddr)
if err != nil {
panic(err)
}
defer conn.Close()
for {
// Receive one datagram and learn who sent it.
var buf [256]byte
r, err := conn.ReadFrom(buf[:])
if err != nil {
panic(err)
}
// Echo it back to the sender.
conn.WriteTo(buf[:r.N], &r.Addr)
}
}
Output:
func (*UDPConn) Close ¶
Close closes the connection. Returns an error if it has already been called.
func (*UDPConn) Read ¶
Read reads a datagram from a connected connection into b.
Read requires a connection from DialUDP; on an unconnected socket it returns ErrAddrNotAvail (use UDPConn.ReadFrom instead). A zero-length datagram is valid and returns (0, nil); Read never returns io.EOF.
func (*UDPConn) ReadFrom ¶
ReadFrom reads a datagram from the connection into b and returns the byte count together with the source address. The buffer should be large enough to hold the datagram; any excess is discarded.
ReadFrom requires an unconnected socket from ListenUDP; on a connected socket it returns ErrAddrNotAvail (use UDPConn.Read instead). A zero-length datagram is valid and reported as N == 0; ReadFrom never returns io.EOF.
func (*UDPConn) RemoteAddr ¶
RemoteAddr returns the remote network address. It is meaningful only for a connected connection (from DialUDP); for an unconnected socket it is the zero UDPAddr.
func (*UDPConn) SetDeadline ¶
SetDeadline sets the read and write deadlines associated with the connection. It is equivalent to calling both SetReadDeadline and SetWriteDeadline.
A deadline is an absolute time after which I/O operations fail instead of blocking. The deadline applies to all future I/O, not just the immediately following call. After a deadline has been exceeded, the connection can be refreshed by setting a deadline in the future.
If the deadline is exceeded a call to a read or write method will return ErrTimeout.
A zero value for t means I/O operations will not time out.
func (*UDPConn) SetReadDeadline ¶
SetReadDeadline sets the deadline for future read calls. A zero value for t means reads will not time out.
func (*UDPConn) SetWriteDeadline ¶
SetWriteDeadline sets the deadline for future write calls. A zero value for t means writes will not time out.
func (*UDPConn) Write ¶
Write writes the datagram in b to a connected connection.
Write requires a connection from DialUDP; on an unconnected socket it returns ErrAddrNotAvail (use UDPConn.WriteTo instead).
func (*UDPConn) WriteTo ¶
WriteTo writes the datagram in b to addr.
WriteTo requires an unconnected socket from ListenUDP; on a connected socket it returns ErrAddrNotAvail (use UDPConn.Write instead).
type UDPRead ¶
UDPRead is the result of UDPConn.ReadFrom: the byte count and the source address.
type UnixAddr ¶
type UnixAddr struct {
Name string // filesystem path of the socket
Net string // "unix" or "unixgram"
}
UnixAddr represents the address of a Unix domain socket endpoint.
func ResolveUnixAddr ¶
ResolveUnixAddr returns the address of a Unix domain socket endpoint.
Known networks are "unix" (stream) and "unixgram" (datagram). The address is a filesystem path; it is not resolved or validated against the filesystem, only carried through, so there is no DNS or service lookup as with TCP/UDP.
Examples:
ResolveUnixAddr("unix", "/tmp/echo.sock")
ResolveUnixAddr("unixgram", "/tmp/dgram.sock")
type UnixConn ¶
type UnixConn struct {
// contains filtered or unexported fields
}
UnixConn is a Unix domain socket connection. Like UDPConn it serves several roles: a connected socket (from DialUnix, with UnixConn.Read/UnixConn.Write) and, for datagrams, an unconnected socket (from ListenUnixgram, exchanging datagrams with arbitrary peers via UnixConn.ReadFrom/UnixConn.WriteTo). An accepted stream connection (from UnixListener.Accept) is also a UnixConn.
The zero value is not usable. A UnixConn must not be copied after use (copies share the underlying socket descriptor and the source-address buffer).
func DialUnix ¶
DialUnix connects to raddr on the named Unix network.
Known networks are "unix" (stream) and "unixgram" (datagram). Use ResolveUnixAddr to obtain raddr (and an optional laddr) from a path.
If laddr is non-nil it is bound first; the bound socket file is removed on UnixConn.Close. For an unnamed local end pass a nil laddr. The returned connection is connected: use UnixConn.Read and UnixConn.Write.
func ListenUnixgram ¶
ListenUnixgram creates an unconnected Unix datagram socket bound to laddr.
The only known network is "unixgram". laddr must be non-nil and name a path; that socket file is removed on UnixConn.Close. The socket is unconnected: exchange datagrams with arbitrary peers via UnixConn.ReadFrom and UnixConn.WriteTo. A peer must itself be bound (also via ListenUnixgram) to be addressable as a reply destination.
func (*UnixConn) Close ¶
Close closes the connection, removing the bound socket file if this connection created one (from ListenUnixgram or a DialUnix with a local address). Returns an error if it has already been called. An unlink failure after a successful close is not surfaced; the close error takes precedence.
func (*UnixConn) Read ¶
Read reads data from a connected connection into b.
Read requires a connection from DialUnix or UnixListener.Accept; on an unconnected socket it returns ErrAddrNotAvail (use UnixConn.ReadFrom). For a stream connection, Read returns 0, io.EOF at end of stream; for a connected datagram socket a zero-length datagram is valid and returns (0, nil).
func (*UnixConn) ReadFrom ¶
ReadFrom reads a datagram from the connection into b and returns the byte count together with the source address. The buffer should be large enough to hold the datagram; any excess is discarded.
ReadFrom requires an unconnected socket from ListenUnixgram; on a connected socket it returns ErrAddrNotAvail (use UnixConn.Read instead). A zero-length datagram is valid and reported as N == 0.
The returned Addr.Name is a view into a per-connection buffer and stays valid only until the next ReadFrom on this connection. An anonymous (unbound) peer has an empty Name.
func (*UnixConn) RemoteAddr ¶
RemoteAddr returns the remote network address. It is meaningful only for a connected connection (from DialUnix or UnixListener.Accept); for an unconnected socket it is the zero UnixAddr.
func (*UnixConn) SetDeadline ¶
SetDeadline sets the read and write deadlines associated with the connection. It is equivalent to calling both SetReadDeadline and SetWriteDeadline.
A deadline is an absolute time after which I/O operations fail with ErrTimeout instead of blocking. A zero value for t means I/O operations will not time out.
func (*UnixConn) SetReadDeadline ¶
SetReadDeadline sets the deadline for future read calls. A zero value for t means reads will not time out.
func (*UnixConn) SetWriteDeadline ¶
SetWriteDeadline sets the deadline for future write calls. A zero value for t means writes will not time out.
func (*UnixConn) Write ¶
Write writes data to a connected connection.
Write requires a connection from DialUnix or UnixListener.Accept; on an unconnected socket it returns ErrAddrNotAvail (use UnixConn.WriteTo). A stream connection writes all of b, looping as the send buffer drains; a connected datagram socket sends b as a single datagram.
func (*UnixConn) WriteTo ¶
WriteTo writes the datagram in b to addr.
WriteTo requires an unconnected socket from ListenUnixgram; on a connected socket it returns ErrAddrNotAvail (use UnixConn.Write instead).
type UnixListener ¶
type UnixListener struct {
// contains filtered or unexported fields
}
UnixListener is a Unix domain stream listener. The zero value is not usable; obtain one from ListenUnix.
func ListenUnix ¶
func ListenUnix(network string, laddr *UnixAddr) (UnixListener, error)
ListenUnix announces on the local Unix address laddr.
The only known network is "unix" (stream). laddr must be non-nil and name a path; that socket file is created on bind and removed on UnixListener.Close.
func (*UnixListener) Accept ¶
func (l *UnixListener) Accept() (UnixConn, error)
Accept waits for and returns the next connection to the listener.
func (*UnixListener) Addr ¶
func (l *UnixListener) Addr() UnixAddr
Addr returns the listener's network address.
func (*UnixListener) Close ¶
func (l *UnixListener) Close() error
Close stops listening and removes the bound socket file. Already accepted connections are not closed. An unlink failure after a successful close is not surfaced; the close error takes precedence.
func (*UnixListener) SetDeadline ¶
func (l *UnixListener) SetDeadline(t time.Time) error
SetDeadline sets the deadline for future Accept calls. An Accept that has no connection ready before t fails with ErrTimeout. The zero value for t clears the deadline (Accept blocks until a connection arrives).
type UnixRead ¶
UnixRead is the result of UnixConn.ReadFrom: the byte count and the source address.