package main import ( "fmt" "net" ) func main() { conn, err := net.Dial("tcp", "google.com:80") if err != nil { fmt.Println(err) return } fmt.Println("Connected to", conn.RemoteAddr()) }
package main import ( "fmt" "net" ) func main() { ln, err := net.Listen("tcp", ":8080") if err != nil { fmt.Println(err) return } defer ln.Close() for { conn, err := ln.Accept() if err != nil { fmt.Println(err) continue } go handleConnection(conn) } } func handleConnection(conn net.Conn) { defer conn.Close() fmt.Println("New connection from", conn.RemoteAddr()) }This code creates a TCP listener on port 8080 and accepts connections in an infinite loop. Each new connection is handled in a separate goroutine by the `handleConnection` function which simply prints the remote address of the connected socket. These examples demonstrate the use of the net package in Go for establishing and handling network connections.