Menu Close

Go – How to compare IP addresses in Go

Here, we will help you to understand how to compare IP addresses in Go. We will learn about Equal() method of net package by example and program.

Equal() method of net package is used to compare IP addresses either IPv4 or IPv6 type in Go.

Function prototype:

func (ip1 IP) Equal(ip2 IP) bool

Input parameters:

ip1: First IP address of type net.IP


ip2: Second IP address of type net.IP to be compared with first IP i.e ip1

Return value:

Equal() function in net package returns true if they are equal else false.

Example with code:

package main

import (
  "fmt"
  "net"
)


func is_ip_addresses_equal(ip1, ip2 net.IP) bool {

    is_equal := ip1.Equal(ip2)

    return is_equal

}

func main() {

    ip1 := net.ParseIP("192.0.2.2")

    ip2 := net.ParseIP("192.0.2.2")

    if ip1 != nil && ip2 != nil {

        fmt.Println("Are both IPs equal: ", is_ip_addresses_equal(ip1, ip2))

    } else {

        fmt.Println("Invalid IP address. IP1: ", ip1, "IP2: ", ip2)
    }

}

Output:

$ go run sample.go

Are both IPs equal: true

Example with different IP address:

package main

import (
  "fmt"
  "net"
)


func is_ip_addresses_equal(ip1, ip2 net.IP) bool {

    is_equal := ip1.Equal(ip2)

    return is_equal

}

func main() {

    ip1 := net.ParseIP("192.0.2.2")

    ip2 := net.ParseIP("192.0.2.5")

    if ip1 != nil && ip2 != nil {

        fmt.Println("Are both IPs equal: ", is_ip_addresses_equal(ip1, ip2))

    } else {

        fmt.Println("Invalid IP address. IP1: ", ip1, "IP2: ", ip2)
    }

}

Output:

$: go run sample.go

Are both IPs equal:  false

Example with Invalid IP address:

package main

import (
  "fmt"
  "net"
)


func is_ip_addresses_equal(ip1, ip2 net.IP) bool {

    is_equal := ip1.Equal(ip2)

    return is_equal

}

func main() {

    ip1 := net.ParseIP("192.0.2.2")

    ip2 := net.ParseIP("192.0.2.523")

    if ip1 != nil && ip2 != nil {

        fmt.Println("Are both IPs equal: ", is_ip_addresses_equal(ip1, ip2))

    } else {

        fmt.Println("Invalid IP address. IP1: ", ip1, "IP2: ", ip2)
    }

}
$ go run sample.go

Invalid IP address. IP1:  192.0.2.2 IP2: <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.

Contact Us