Find out if an IP is within a range of IPs

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

    I prefer this approach for converting the IP address to an integer for range comparison:

    # n_ip("192.1.1.23") will return the number 192001001023
    def n_ip(input)
      input.split(".").collect{|p| p.rjust(3, "0")}.join.to_i
    end
    
    def ip_in_range?(from, to, given)
      (n_ip(from)..n_ip(to).include?(n_ip(given))
    end
    

    Now you can check the value as follows:

    >> ip_in_range?("192.168.0.0",  "192.168.0.255","192.168.0.200")
    ip_in_range?("192.168.0.0",  "192.168.0.255","192.168.0.200")
    => true
    >> ip_in_range?("192.168.0.0",  "192.168.0.255", "192.168.1.200")
    ip_in_range?("192.168.0.0",  "192.168.0.255", "192.168.1.200")
    => false
    

    The integer returned is not a 32 bit representation of the IP address. The logic will work for all valid IP addresses.

提交回复
热议问题