net is the foundation every network-facing Go program builds on: dialing and listening for TCP, UDP, and Unix sockets, parsing and inspecting IP addresses, and resolving hostnames. net/http, net/rpc, and this site's own TCP server and WebSocket guides all sit on top of it.
net.Dial takes a network ("tcp", "udp", "unix") and an address, returning a Conn once the connection succeeds.
conn, err := net.Dial("tcp", "example.com:80")
if err != nil {
log.Fatal(err)
}
defer conn.Close()Examples
Dial blocks until the connection is established. The returned Conn is a plain io.ReadWriteCloser, the same interface a file or a bytes.Buffer could satisfy.
conn, err := net.Dial("tcp", "example.com:80")
if err != nil {
log.Fatal(err)
}
defer conn.Close()
fmt.Fprint(conn, "GET / HTTP/1.1\r\nHost: example.com\r\nConnection: close\r\n\r\n")
status, err := bufio.NewReader(conn).ReadString('\n')
fmt.Print(status)HTTP/1.1 200 OKA listener hands back one Conn per Accept call. Handling each connection in its own goroutine is the standard shape for a concurrent server.
ln, err := net.Listen("tcp", ":9000")
if err != nil {
log.Fatal(err)
}
defer ln.Close()
for {
conn, err := ln.Accept()
if err != nil {
continue
}
go func(c net.Conn) {
defer c.Close()
io.Copy(c, c) // echo whatever the client sends
}(conn)
}# blocks, serving connections until the process exitsResolving up front, instead of passing a bare string to Dial or Listen, is how a program validates an address before acting on it.
addr, err := net.ResolveTCPAddr("tcp", "127.0.0.1:9000")
if err != nil {
log.Fatal(err)
}
fmt.Println(addr.IP, addr.Port)127.0.0.1 9000SplitHostPort and JoinHostPort handle the bracket syntax IPv6 addresses need in a "host:port" string, so hand-rolled string.Split on ":" breaks on them silently.
host, port, err := net.SplitHostPort("localhost:8080")
fmt.Println(host, port, err)
fmt.Println(net.JoinHostPort("localhost", "8080"))localhost 8080
localhost:8080 Core interfaces
A generic stream-oriented network connection. TCPConn, UnixConn, and others all satisfy it.
- Read(b []byte) (n int, err error)
- Write(b []byte) (n int, err error)
- Close() error
- LocalAddr() Addr
- RemoteAddr() Addr
- SetDeadline(t time.Time) error
- SetReadDeadline(t time.Time) error
- SetWriteDeadline(t time.Time) error
Accepts incoming connections on a listening socket.
- Accept() (Conn, error)
- Close() error
- Addr() Addr
A packet-oriented connection with no fixed remote peer, which is what UDP uses instead of Conn.
- ReadFrom(p []byte) (n int, addr Addr, err error)
- WriteTo(p []byte, addr Addr) (n int, err error)
- Close() error
- LocalAddr() Addr
- SetDeadline(t time.Time) error
An address on some network. TCPAddr, UDPAddr, and UnixAddr all satisfy it.
- Network() string
- String() string
Satisfied by every error this package returns. Timeout reports whether the failure was a deadline expiring.
- Timeout() bool
Dialing and listening
| Function | Description |
|---|---|
Dial(network, address string) (Conn, error) conn, err := net.Dial("tcp", "example.com:80") | Connects to address over network ("tcp", "udp", "unix", ...), blocking until connected or an error occurs. |
DialTimeout(network, address string, timeout time.Duration) (Conn, error) | Like Dial, failing instead of blocking past timeout. |
type Dialer struct{ Timeout time.Duration; Deadline time.Time; LocalAddr Addr; ... } | Configurable dialer; the zero value behaves like the package-level Dial. |
(*Dialer) Dial(network, address string) (Conn, error) | Dials using the Dialer's configured options. |
(*Dialer) DialContext(ctx context.Context, network, address string) (Conn, error) | Like Dial, cancelable through ctx instead of a fixed timeout. |
Listen(network, address string) (Listener, error) ln, err := net.Listen("tcp", ":8080") | Opens a listening socket on address for a stream-oriented network. |
ListenPacket(network, address string) (PacketConn, error) | Opens a listening socket for a packet-oriented network like UDP. |
type ListenConfig struct{ Control func(...) error; KeepAlive time.Duration } | Configurable listener setup, the Listen/ListenPacket equivalent of Dialer. |
TCP
| Function | Description |
|---|---|
type TCPAddr struct{ IP IP; Port int; Zone string } | A resolved TCP endpoint. |
ResolveTCPAddr(network, address string) (*TCPAddr, error) addr, err := net.ResolveTCPAddr("tcp", "127.0.0.1:9000") | Parses address ("host:port") into a TCPAddr, resolving a hostname if needed. |
DialTCP(network string, laddr, raddr *TCPAddr) (*TCPConn, error) | Like Dial, typed to TCP and a resolved address instead of a string. |
ListenTCP(network string, laddr *TCPAddr) (*TCPListener, error) | Like Listen, typed to TCP. |
type TCPListener struct{ ... } | A TCP-specific Listener. |
(*TCPListener) Accept() (Conn, error) / AcceptTCP() (*TCPConn, error) | Blocks until a client connects, returning the new connection. |
type TCPConn struct{ ... } | A TCP-specific Conn, with a few extra methods beyond the interface. |
(*TCPConn) SetKeepAlive(keepalive bool) error / SetKeepAlivePeriod(d time.Duration) error | Enables OS-level TCP keepalive probes and sets their interval. |
(*TCPConn) SetNoDelay(noDelay bool) error | Disables Nagle's algorithm when true, so small writes go out immediately instead of being buffered and coalesced. |
(*TCPConn) CloseRead() error / CloseWrite() error | Half-closes just one direction of the connection, signaling EOF to the peer while the other direction stays open. |
UDP
| Function | Description |
|---|---|
type UDPAddr struct{ IP IP; Port int; Zone string } | A resolved UDP endpoint. |
ResolveUDPAddr(network, address string) (*UDPAddr, error) | Parses address into a UDPAddr. |
DialUDP(network string, laddr, raddr *UDPAddr) (*UDPConn, error) | Opens a UDP socket with a fixed remote peer. |
ListenUDP(network string, laddr *UDPAddr) (*UDPConn, error) | Opens a UDP socket that can receive from any peer. |
(*UDPConn) ReadFromUDP(b []byte) (n int, addr *UDPAddr, err error) | Reads one packet, reporting which address it came from. |
(*UDPConn) WriteToUDP(b []byte, addr *UDPAddr) (n int, err error) | Sends one packet to addr. |
Unix domain sockets
| Function | Description |
|---|---|
type UnixAddr struct{ Name, Net string } | A Unix domain socket address, a filesystem path rather than a host and port. |
ResolveUnixAddr(network, address string) (*UnixAddr, error) | Parses a filesystem path into a UnixAddr. |
DialUnix(network string, laddr, raddr *UnixAddr) (*UnixConn, error) | Connects to a Unix domain socket. |
ListenUnix(network string, laddr *UnixAddr) (*UnixListener, error) | Listens on a Unix domain socket path. |
IP addresses and networks
| Function | Description |
|---|---|
type IP []byte | An IPv4 or IPv6 address, stored as 4 or 16 bytes. |
ParseIP(s string) IP net.ParseIP("192.168.1.10") | Parses a dotted-decimal or hex-colon address string; returns nil on malformed input. |
(IP) String() string | Formats the address back to its standard text form. |
(IP) To4() IP / To16() IP | Returns the address in 4-byte or 16-byte form, or nil if it doesn't fit that form. |
(IP) Equal(x IP) bool | Compares two IPs, treating an IPv4 address and its IPv4-in-IPv6 form as equal. |
(IP) IsLoopback() bool / IsPrivate() bool / IsMulticast() bool / IsUnspecified() bool | Classifies an address by its assigned range. |
type IPAddr struct{ IP IP; Zone string } | An IP address plus an optional IPv6 zone. |
ResolveIPAddr(network, address string) (*IPAddr, error) | Resolves a hostname or address string to an IPAddr. |
type IPMask []byte | A bitmask the same length as an IP, used to derive a network from an address. |
CIDRMask(ones, bits int) IPMask net.CIDRMask(24, 32) // 255.255.255.0 | Builds a mask with ones leading 1-bits out of bits total. |
type IPNet struct{ IP IP; Mask IPMask } | An IP network: a base address plus a mask. |
ParseCIDR(s string) (IP, *IPNet, error) | Parses CIDR notation like "10.0.0.0/24" into an address and its containing network. |
(*IPNet) Contains(ip IP) bool | Reports whether ip falls inside the network. |
DNS lookups
| Function | Description |
|---|---|
LookupHost(host string) ([]string, error) | Resolves a hostname to its IP addresses as strings. |
LookupIP(host string) ([]IP, error) | Like LookupHost, returning parsed IP values instead of strings. |
LookupAddr(addr string) ([]string, error) | Reverse DNS: resolves an IP address to its hostnames. |
LookupPort(network, service string) (int, error) | Resolves a named service (e.g. "https") to its port number for network. |
LookupCNAME(host string) (string, error) | Resolves a host's canonical name. |
LookupMX(name string) ([]*MX, error) / LookupNS / LookupTXT / LookupSRV | Resolve the corresponding DNS record type for name. |
type Resolver struct{ PreferGo bool; Dial func(...) (Conn, error); ... } | A configurable stand-in for the package-level Lookup functions, e.g. to force Go's own resolver or a custom DNS server. |
Helpers, interfaces, and errors
| Function | Description |
|---|---|
JoinHostPort(host, port string) string net.JoinHostPort("localhost", "8080") | Combines a host and port into "host:port", bracketing an IPv6 host. |
SplitHostPort(hostport string) (host, port string, err error) net.SplitHostPort("localhost:8080") | The inverse of JoinHostPort. |
Interfaces() ([]Interface, error) | Lists the machine's network interfaces. |
type Interface struct{ Index int; MTU int; Name string; HardwareAddr HardwareAddr; Flags Flags } | One network interface's identity and status. |
(*Interface) Addrs() ([]Addr, error) | Lists the addresses assigned to an interface. |
type OpError struct{ Op, Net string; Addr Addr; Err error } | Wraps a lower-level error with the operation and address that failed; what most net errors actually are. |
type DNSError struct{ Err, Name string; IsTimeout, IsNotFound bool } | The error type DNS lookup failures return. |
ErrClosed error | Returned by operations on a connection or listener that's already been closed. |
net/http is built entirely on top of this package: http.ListenAndServe calls net.Listen internally and hands each accepted connection to its own request-handling goroutine.