Golang - 检查IP地址是否在网络中

时间:2017-04-07 09:30:42

标签: networking go ip-address subnet

假设:

  • 网络地址A:(172.17.0.0/16
  • 和来自主机B的IP地址:(172.17.0.2/16

我们如何判断B是否在A?

所有地址都是以下列形式的字符串变量:[IP address in dot-decimal notation]/[subnet mask]。我应该尝试通过操纵字符串(初步想法)来做到这一点。有不同的路径吗?

以下是Python的相同问题:

和Go的另一种方法:

3 个答案:

答案 0 :(得分:11)

Go net package包括以下功能:

这应该可以满足您的需求。

答案 1 :(得分:5)

基于Zoyd的反馈......

https://play.golang.org/p/wdv2sPetmt

package main

import (
    "fmt"
    "net"
)

func main() {

    A := "172.17.0.0/16"
    B := "172.17.0.2/16"

    ipA,ipnetA,_ := net.ParseCIDR(A)
    ipB,ipnetB,_ := net.ParseCIDR(B)

    fmt.Println("Network address A: ", A)
    fmt.Println("IP address      B: ", B)
    fmt.Println("ipA              : ", ipA)
    fmt.Println("ipnetA           : ", ipnetA)
    fmt.Println("ipB              : ", ipB)
    fmt.Println("ipnetB           : ", ipnetB)


    fmt.Printf("\nDoes A (%s) contain: B (%s)?\n", ipnetA, ipB)

    if ipnetA.Contains(ipB) {
        fmt.Println("yes")
    } else {
        fmt.Println("no")
    }

}

答案 2 :(得分:0)

基于tgogos的答案:

package main

import (
    "fmt"
    "net"
)

func main() {
    A := "172.17.0.0/16"
    B := "172.17.0.2"

    _, ipnetA, _ := net.ParseCIDR(A)
    ipB := net.ParseIP(B)

    fmt.Printf("\nDoes A (%s) contain: B (%s)?\n", ipnetA, ipB)

    if ipnetA.Contains(ipB) {
        fmt.Println("yes")
    } else {
        fmt.Println("no")
    }
}