Menu Close

Go – How to check loopback address in Go

Here, we will help you to understand how to check loopback address in Go. We will learn about IsLoopback() method to check loopback address in go.

IsLoopback() method of net package validates whether ip is a loopback address or not in Go.

Function prototype:

func (ip IP) IsLoopback() bool

parameters:

ip: loopback ip address of type net.IP

Return value:

IsLoopback() function in net package returns true if IP address is loopback IP else false.

Example with code:

package main

import (
  "fmt"
  "net"
)


func main() {

    // 127.0.0.1 is a default loopback IP
    ip_addr := net.ParseIP("127.0.0.1")

    if ip_addr != nil {

        is_loopback_ip := ip_addr.IsLoopback()

        fmt.Println("Is IP loopback: ", is_loopback_ip)

    } else {

        fmt.Println("Invalid IP address: ", ip_addr)
    }

}

Output:

$ go run sample.go

Is IP loopback: true

Example with invalid loopback IP address:

package main

import (
  "fmt"
  "net"
)


func main() {

    // 127.0.0.1 is a default loopback IP
    ip_addr := net.ParseIP("10.1.1.1")

    if ip_addr != nil {

        is_loopback_ip := ip_addr.IsLoopback()

        fmt.Println("Is IP loopback: ", is_loopback_ip)

    } else {

        fmt.Println("Invalid IP address: ", ip_addr)
    }

}

Output:

$: go run sample.go

Is IP loopback:  false

Example with Invalid IP address:

package main

import (
  "fmt"
  "net"
)


func main() {

    // 127.0.0.1 is a default loopback IP
    ip_addr := net.ParseIP("900.1.1.1")

    if ip_addr != nil {

        is_loopback_ip := ip_addr.IsLoopback()

        fmt.Println("Is IP loopback: ", is_loopback_ip)

    } else {

        fmt.Println("Invalid IP address: ", ip_addr)
    }

}
$ go run sample.go

Invalid IP address:  <nil>

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. Required fields are marked *