Find out if an IP is within a range of IPs

前端 未结 7 869
萌比男神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:31

    I would use this killer little function to convert the IP addresses into integers, and then compare those.

    def ip_addr_in_range?(low, high, addr)
      int_addr = numeric_ip(addr)
      int_addr <= numeric_ip(high) && int_addr >= numeric_ip(low)
    end
    
    def numeric_ip(ip_str)
      ip_str.split('.').inject(0) { |ip_num, part| ( ip_num << 8 ) + part.to_i }
    end
    
    def test_ip_addr_in_range(low, high, addr, expected)
      result = ip_addr_in_range?(low, high, addr)
      puts "#{addr} #{(expected ? 'should' : 'should not')} be within #{low} and #{high}: #{(expected == result ? 'PASS' : 'FAIL')}"
    end
    
    
    test_ip_addr_in_range("192.168.0.0", "192.168.0.255", "192.168.0.200", true)
    test_ip_addr_in_range("192.168.0.0", "192.168.0.155", "192.168.0.200", false)
    test_ip_addr_in_range("192.168.0.0", "192.168.255.255", "192.168.100.200", true)
    test_ip_addr_in_range("192.168.0.0", "192.168.100.255", "192.168.150.200", false)
    test_ip_addr_in_range("192.168.255.255", "192.255.255.255", "192.200.100.100", true)
    test_ip_addr_in_range("192.168.255.255", "192.255.255.255", "192.100.100.100", false)
    test_ip_addr_in_range("192.168.255.255", "255.255.255.255", "200.200.100.100", true)
    test_ip_addr_in_range("192.168.255.255", "255.255.255.255", "180.100.100.100", false)
    
    $ ruby ip_range.rb
    192.168.0.200 should be within 192.168.0.0 and 192.168.0.255: PASS
    192.168.0.200 should not be within 192.168.0.0 and 192.168.0.155: PASS
    192.168.100.200 should be within 192.168.0.0 and 192.168.255.255: PASS
    192.168.150.200 should not be within 192.168.0.0 and 192.168.100.255: PASS
    192.200.100.100 should be within 192.168.255.255 and 192.255.255.255: PASS
    192.100.100.100 should not be within 192.168.255.255 and 192.255.255.255: PASS
    200.200.100.100 should be within 192.168.255.255 and 255.255.255.255: PASS
    180.100.100.100 should not be within 192.168.255.255 and 255.255.255.255: PASS
    

提交回复
热议问题