Package net

The net package provides a platform-independent interface to the network protocol primitives used in implementing network servers and clients. It is intended to be used for network programming in Go.

The net package is fundamental for building network applications in Go. It abstracts away many of the low-level details of network communication, allowing developers to focus on application logic.

Overview

This package supports the following network primitives:

Key Types and Functions

IP Addresses

The IP type represents an IP address. It can be either an IPv4 or IPv6 address.

type IP []byte

Key functions include:

TCP Connections

The net package provides types for working with TCP connections.

TCP is a connection-oriented protocol that guarantees reliable, ordered delivery of data.

Key types and functions:

Conn Interface

Represents a network connection. It embeds the io.Reader and io.Writer interfaces.

type Conn interface { 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 }

Listener Interface

A Listener is an object that network operations can be performed on.

type Listener interface { Accept() (Conn, error) Close() error Addr() Addr }

UDP Datagrams

For connectionless communication using UDP.

UDP is a connectionless protocol that does not guarantee delivery or order.

Key functions:

UDPConn Type

Represents a UDP network connection.

type UDPConn struct { ... }

DNS Resolution

The net package includes functions for resolving hostnames and service names.

Example Usage

TCP Client

package main

import (
	"fmt"
	"log"
	"net"
)

func main() {
	conn, err := net.Dial("tcp", "example.com:80")
	if err != nil {
		log.Fatalf("Failed to dial: %v", err)
	}
	defer conn.Close()

	fmt.Fprintf(conn, "GET / HTTP/1.0\\r\\n\\r\\n")
	
	buffer := make([]byte, 1024)
	n, err := conn.Read(buffer)
	if err != nil {
		log.Fatalf("Failed to read: %v", err)
	}
	fmt.Printf("Received: %s\\n", buffer[:n])
}

TCP Server

package main

import (
	"fmt"
	"log"
	"net"
)

func main() {
	listener, err := net.Listen("tcp", ":8080")
	if err != nil {
		log.Fatalf("Failed to listen: %v", err)
	}
	defer listener.Close()

	fmt.Println("Server listening on :8080")

	for {
		conn, err := listener.Accept()
		if err != nil {
			log.Printf("Failed to accept connection: %v", err)
			continue
		}
		go handleConnection(conn)
	}
}

func handleConnection(conn net.Conn) {
	defer conn.Close()
	fmt.Printf("Accepted connection from %s\\n", conn.RemoteAddr())

	buffer := make([]byte, 1024)
	n, err := conn.Read(buffer)
	if err != nil {
		log.Printf("Error reading from connection: %v", err)
		return
	}
	fmt.Printf("Received: %s\\n", buffer[:n])

	_, err = conn.Write([]byte("Hello from Go server!\\n"))
	if err != nil {
		log.Printf("Error writing to connection: %v", err)
	}
}