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.
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:
- IP addresses and IP addresses: For representing and manipulating IP addresses.
- TCP and UDP: For connection-oriented and connectionless datagram communication, respectively.
- Unix domain sockets: For inter-process communication on Unix-like systems.
- DNS resolution: For looking up hostnames and service names.
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:
ParseIP(s string) IP
: Parses an IP address string.ip.IsLoopback() bool
: Reports whether the IP address is a loopback address.ip.IsGlobalUnicast() bool
: Reports whether the IP address is a global unicast address.
TCP Connections
The net
package provides types for working with TCP connections.
Key types and functions:
Dial(network, address string) (Conn, error)
: Establishes a TCP connection.Listen(network, address string) (Listener, error)
: Creates a TCP listener.
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.
Key functions:
DialUDP(network string, laddr, raddr *UDPAddr) (*UDPConn, error)
: Establishes a UDP connection.ListenUDP(network string, laddr *UDPAddr) (*UDPConn, error)
: Creates a UDP listener.
UDPConn
Type
Represents a UDP network connection.
type UDPConn struct { ... }
DNS Resolution
The net
package includes functions for resolving hostnames and service names.
LookupHost(host string) ([]string, error)
: Returns a list of IP addresses for the given host.LookupPort(network, service string) (port int, err error)
: Returns the port number for a service name.
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)
}
}