【问题标题】:Check if an IP falls into an IP range using sh?使用 sh 检查 IP 是否属于 IP 范围?
【发布时间】:2021-05-19 18:23:09
【问题描述】:

假设我有一个 IP 173.245.50.16,我想检查它是否属于Cloudflare's IP ranges。这基本上归结为:

network_address(173.245.50.16/20) == 173.245.48.0
|| network_address(173.245.50.16/22) == 103.21.244.0
|| ...

对吗?好吧,我不确定这里的术语,但希望你明白这一点。

这如何转化为 sh 代码?

【问题讨论】:

    标签: sh ip-address cidr netmask


    【解决方案1】:

    我想出了什么:

    cf_ip_ranges=`curl -sS https://www.cloudflare.com/ips-v4`
    is_cf_ip() {
        local ip=$1
        local range=$(echo "$cf_ip_ranges" | while IFS= read -r; do
            net=${REPLY%/*}
            n=${REPLY#*/}
            if [ "`ipv4calc --network "$ip/$n"`" = "$net" ]; then
                echo "$REPLY"
                break
            fi
        done)
        if [ "$range" ]; then
            return 0
        else
            return 1
        fi
    }
    if is_cf_ip 8.8.8.8; then
        echo true
    else
        echo false
    fi
    if is_cf_ip 173.245.50.16; then
        echo true
    else
        echo false
    fi
    

    这里我使用 Perl 的Net::IPv4Addr module

    【讨论】:

      猜你喜欢
      • 2018-01-09
      • 2017-05-21
      • 2014-09-16
      • 2012-03-26
      • 2013-08-22
      • 1970-01-01
      • 1970-01-01
      • 2011-01-09
      • 1970-01-01
      相关资源
      最近更新 更多