LoginSignup
3
1

More than 5 years have passed since last update.

GoでCIDRブロック内にIPが含まれているか判定

Last updated at Posted at 2016-12-17

Goで、CIDRブロック内に指定IPが含まれているか判定するスニペット

string型のcidr, ipを渡して、含まれているかをboolで返す。

cidr.go
package cidr

import (
    "log"
    "net"
)

// isIncluededInCIDR reports whether the cidr includes the given ip.
func isIncluededInCIDR(cidr, ip string) bool {
    _, cidrNet, err := net.ParseCIDR(cidr)
    if err != nil {
        log.Fatal(err)
        return false
    }

    targetIP := net.ParseIP(ip)
    return cidrNet.Contains(targetIP)
}
3
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1