Standard library / net

net.ListenTCP()

Bind a local TCP listener; port zero requests an available port. Close when finished. Expected stdout: 'tcp\n'.

Formal Syntax & Structure

go syntaxgo
func ListenTCP(network string, laddr *TCPAddr) (*TCPListener, error)

Parameters & Attributes

NameTypeDescription
networkstringNetwork family such as tcp4 or udp4.
laddr*TCPAddrLocal bind address; nil selects a local address for dialing.

Return Value

(*TCPListener, error)

Operation result; check errors and validity indicators when returned.

Working Example

Example Snippetgo
package main
import (  "fmt"  "net")
func main() {  l := must(net.ListenTCP("tcp4", &net.TCPAddr{IP: net.IPv4(127, 0, 0, 1)}))  defer l.Close()  fmt.Println(l.Addr().Network())}
func must[T any](v T, e error) T {  if e != nil {    panic(e)  }  return v}func check(e error) {  if e != nil {    panic(e)  }}
Go Reference