Home  >  Article  >  Backend Development  >  How to Efficiently Check if an IP Address is Within a Range in Go?

How to Efficiently Check if an IP Address is Within a Range in Go?

DDD
DDDOriginal
2024-11-11 15:20:03783browse

How to Efficiently Check if an IP Address is Within a Range in Go?

Checking IP Addresses within a Range Efficiently in Go

Determining whether an IP address falls within a specified range is a common requirement in various network operations. In Go, there are several approaches for addressing this task.

Fastest Method: bytes.Compare

One of the most efficient methods is to use the bytes.Compare function to compare the byte representation of the IP addresses.

import (
    "bytes"
    "net"
)

// Check if an IP address is within a range
func check(trial, start, end net.IP) bool {
    if start.To4() == nil || end.To4() == nil || trial.To4() == nil {
        return false
    }
    return bytes.Compare(trial, start) >= 0 && bytes.Compare(trial, end) <= 0
}

In this approach, we first check if the given IP addresses are valid IPv4 addresses. We then use bytes.Compare to compare the byte representations of the trial IP and the start and end points of the range. If the comparison results in a non-negative value for both checks, it signifies that the IP address is within the range.

Example Usage

The following code demonstrates the usage of the bytes.Compare method:

import (
    "fmt"
    "net"
)

var (
    ip1 = net.ParseIP("216.14.49.184")
    ip2 = net.ParseIP("216.14.49.191")
)

func main() {
    check := func(ip string) {
        trial := net.ParseIP(ip)
        res := check(trial, ip1, ip2)
        fmt.Printf("%v is %v within range %v to %v\n", trial, res, ip1, ip2)
    }
    check("1.2.3.4")
    check("216.14.49.185")
    check("216.14.49.191")
}

Output:

1.2.3.4 is false within range 216.14.49.184 to 216.14.49.191
216.14.49.185 is true within range 216.14.49.184 to 216.14.49.191
216.14.49.191 is true within range 216.14.49.184 to 216.14.49.191

The above is the detailed content of How to Efficiently Check if an IP Address is Within a Range in Go?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn