Find out if an IP is within a range of IPs

前端 未结 7 1061
萌比男神i
萌比男神i 2021-01-30 09:18

How can you tell if an ip, say 62.156.244.13 is within the range of 62.0.0.0 and 62.255.255.255

7条回答
  •  忘掉有多难
    2021-01-30 09:32

    Don't make it any harder than it has to be.

    def check_ip(ip)
      '62.0.0.0' < ip and ip < '62.255.255.255'
    end
    
    check_ip '62.156.244.13' #=> true
    

    Edit: Or, if you're using Rails / ActiveSupport:

    def check_ip(ip)
      ip.starts_with? '62'
    end
    
    check_ip '62.156.244.13' #=> true
    

提交回复
热议问题