duandanai6470 2016-12-20 11:01
浏览 82
已采纳

转到-检查IP地址是否在专用网络空间中

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.

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.

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.

  • 写回答

2条回答 默认 最新

  • dtiopy6088 2018-06-12 20:14
    关注

    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
            "::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 {
        for _, block := range privateIPBlocks {
            if block.Contains(ip) {
                return true
            }
        }
        return false
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 NAO机器人的录音程序保存问题
  • ¥15 C#读写EXCEL文件,不同编译
  • ¥15 如何提取csv文件中需要的列,将其整合为一篇完整文档,并进行jieba分词(语言-python)
  • ¥15 MapReduce结果输出到HBase,一直连接不上MySQL
  • ¥15 扩散模型sd.webui使用时报错“Nonetype”
  • ¥15 stm32流水灯+呼吸灯+外部中断按键
  • ¥15 将二维数组,按照假设的规定,如0/1/0 == "4",把对应列位置写成一个字符并打印输出该字符
  • ¥15 NX MCD仿真与博途通讯不了啥情况
  • ¥15 win11家庭中文版安装docker遇到Hyper-V启用失败解决办法整理
  • ¥15 gradio的web端页面格式不对的问题