检查IP地址是否在专用网络空间中 [英] Check if IP address is in private network space

查看:86
本文介绍了检查IP地址是否在专用网络空间中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用一个程序,该程序接受来自客户端的URL,并使用net/http软件包获取它们.在进行进一步处理之前,我想检查URL是否映射到私有(不可路由/RFC1918网络)地址空间.

I have a program in go which accepts URLs from clients and gets them using the net/http package. Before doing further processing, I would like to check if the URL maps to private (non-routable / RFC1918 networks) address space.

直接方法是执行一个明确的DNS请求并检查已知私有范围的地址.之后,对URL执行HTTP GET请求.

The straight-forward way would be to perform an explicit DNS request and check the address for the known private ranges. After that, perform the HTTP GET request for the URL.

是否有更好的方法来做到这一点?最好与http.Client集成,以便可以将其作为GET请求的一部分执行.

Is there a better way to accomplish this? Preferably integrating with http.Client so it can be performed as a part of the GET request.

推荐答案

您可能还希望包括对回送(IPv4或IPv6)和/或IPv6链接本地或唯一本地地址的检查.这是一个示例,其中列出了RFC1918地址以及其他地址,并以isPrivateIP(ip net.IP)的形式对其进行了简单检查:

You might also want to include checks for loopback (IPv4 or IPv6) and/or IPv6 link-local or unique-local addresses. Here is an example with a list of RFC1918 address plus these others and a simple check against them as isPrivateIP(ip net.IP):

var privateIPBlocks []*net.IPNet

func init() {
    for _, cidr := range []string{
        "127.0.0.0/8",    // IPv4 loopback
        "10.0.0.0/8",     // RFC1918
        "172.16.0.0/12",  // RFC1918
        "192.168.0.0/16", // RFC1918
        "169.254.0.0/16", // RFC3927 link-local
        "::1/128",        // IPv6 loopback
        "fe80::/10",      // IPv6 link-local
        "fc00::/7",       // IPv6 unique local addr
    } {
        _, block, err := net.ParseCIDR(cidr)
        if err != nil {
            panic(fmt.Errorf("parse error on %q: %v", cidr, err))
        }
        privateIPBlocks = append(privateIPBlocks, block)
    }
}

func isPrivateIP(ip net.IP) bool {
    if ip.IsLoopback() || ip.IsLinkLocalUnicast() || ip.IsLinkLocalMulticast() {
        return true
    }

    for _, block := range privateIPBlocks {
        if block.Contains(ip) {
            return true
        }
    }
    return false
  }

这篇关于检查IP地址是否在专用网络空间中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆