Skip to content
Tutorials Center
My learning

Topics

Go Reference ยท Networking and the Web

Go net package

Reference for the Go net package: Listen, Accept, Dial, Conn, UDP with ListenPacket, SplitHostPort, IP and CIDR parsing, deadlines and error handling.

The package net is Go's portable interface to network I/O. It covers TCP, UDP, IP and Unix domain sockets, name lookups, and helpers for addresses. net/http is built on top of it. You use net directly when you write your own protocol, a proxy, a health check, or a tool that needs a raw connection.

The two core ideas are net.Listener (waits for incoming connections with Accept) and net.Conn (a bidirectional byte stream with Read, Write, Close and deadlines). A client gets a Conn from net.Dial; a server gets one from listener.Accept(). Both sides then simply read and write.

Go
ln, err := net.Listen("tcp", "127.0.0.1:0") // port 0: let the OS pick a free port
conn, err := net.Dial("tcp", ln.Addr().String())

Try it

Go A TCP echo server and client on loopback

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Go Addresses, CIDR and a deadline

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Syntax

Go
func Listen(network, address string) (Listener, error)
func Dial(network, address string) (Conn, error)
func DialTimeout(network, address string, timeout time.Duration) (Conn, error)
func ListenPacket(network, address string) (PacketConn, error)
func SplitHostPort(hostport string) (host, port string, err error)
func JoinHostPort(host, port string) string
func ParseIP(s string) IP
func ParseCIDR(s string) (IP, *IPNet, error)
func Pipe() (Conn, Conn)

type Listener interface {
	Accept() (Conn, error)
	Close() error
	Addr() Addr
}
Name Description
network "tcp", "tcp4", "tcp6", "udp", "udp4", "udp6", "unix", "unixgram" and "ip" forms.
address host:port. An empty host (":8080") listens on all interfaces; port 0 picks a free port. IPv6 hosts use brackets.
Conn Read, Write, Close, LocalAddr, RemoteAddr, SetDeadline, SetReadDeadline, SetWriteDeadline.

Errors: most failures are *net.OpError, which wraps the cause (syscall.ECONNREFUSED, a *net.DNSError, os.ErrDeadlineExceeded). Operating on a closed connection returns an error that satisfies errors.Is(err, net.ErrClosed).

Usage notes

  • Streams have no message boundaries. A single Write may arrive as several Read calls, and several writes as one. Frame messages with newlines, length prefixes or a scanner.
  • Deadlines are absolute times, not durations, and apply to the next call only after you set them again. Set them before each read or write, or use Dialer with Timeout.
  • Use a net.Dialer for control: Timeout, KeepAlive, LocalAddr, and DialContext(ctx, ...) so a cancelled context aborts the connect.
  • Graceful close. Closing a listener makes the pending Accept return an error; treat it as the signal to stop the accept loop.
  • One goroutine per connection is the usual, cheap pattern. Always defer conn.Close().
  • Security. Bind to 127.0.0.1 unless you want the service reachable from the network.
  • Newer addresses. The package net/netip offers small, comparable Addr and Prefix value types that are better map keys than net.IP.
  • Name resolution. net.LookupHost and net.LookupIP use the system resolver; the sandbox for these examples has no network, so loopback is used here.