What is the net.Listen function in Go?

Overview

The Listen function of the net package in Go creates servers and listens for incoming connections on a local network address.

To use the Listen function, we’ll import the net package into our program as shown below:

import (
   "net"
)

Syntax

The syntax of the Listen function is shown below:

Listen(network, address string) (Listener, error)

Parameters

The Listen function accepts the following parameters:

  • network: The named network for communication, e.g., TCP, UDP, IP, etc.

  • address: The address of the host server to listen on for connections.

Note: The list of supported networks and rules for their corresponding hosts can be found here.

Return value

The Listen function returns a Listener object that represents a server and an error object.

If the Listen function is able to listen on the specified address successfully, the error object has a value of nil.

Example

The code below shows how the Listen function works in Go.

package main
// import necessary packages
import (
"net"
"fmt"
)
func main(){
// initialize the address port number of the server
port := ":8000"
// Set up a listener on port 8080 for tcp connections
ln, err := net.Listen("tcp", port)
// check if server was successfully created
if err != nil {
fmt.Println("The following error occured", err)
} else {
fmt.Println("The listener object has been created:", ln)
}
}

Explanation

  • Lines 4–7: We import the net and fmt packages.
  • Line 12: We initialize the port number on which the Listen function will listen.
  • Line 15: We use the Listen function to create a server that listens for tcp connections on the specified port.
  • If the server is successfully created, err will be nil, and the corresponding message will be output. Otherwise, the if statement in line 18 will detect the error and print the relevant message if an error occurs.

Free Resources