Menu Close

Go – How to get port of given network and service in Go

Here, we will help you to understand how to get port of given network and service in Go. We will learn about LookupPort() method to get port number in go.

Function prototype:

func LookupPort(network, serviceĀ string) (port int, err error)

Input parameters:

Network: Network name like TCP, UDP

service: ssh, http, https

Return value:

LookupPort looks up the port for the given network and service.

Example with code:

package main

import (
  "fmt"
  "net"
)


func main() {

    port, err := net.LookupPort("tcp", "http")

    if err == nil {

        fmt.Println("Port number: ", port)

    } else {

        fmt.Println("Lookup port is failed. Error is: ", err)

    }

}

Output:

$ go run sample.go

Port number: 80

Example-2 with code:

package main

import (
  "fmt"
  "net"
)


func main() {

    port, err := net.LookupPort("tcp", "ssh")

    if err == nil {

        fmt.Println("Port number: ", port)

    } else {

        fmt.Println("Lookup port is failed. Error is: ", err)

    }

}

Output:

$: go run sample.go

Port number:  22

Example with code with invalid service name:

package main

import (
  "fmt"
  "net"
)


func main() {

    port, err := net.LookupPort("tcp", "invalidService")

    if err == nil {

        fmt.Println("Port number: ", port)

    } else {

        fmt.Println("Lookup port is failed. Error is: ", err)

    }

}

Output:

$: go run sample.go

Lookup port is failed. Error is:  lookup tcp/invalidService: nodename nor servname provided, or not known

To learn more about golang, Please refer given below link:

https://www.techieindoor.com/go-lang-tutorial/

References:

https://golang.org/doc/
https://golang.org

Posted in golang, net

Leave a Reply

Your email address will not be published.

Contact Us