Find out if an IP is within a range of IPs

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

    >> require "ipaddr"
    => true
    >> low = IPAddr.new("62.0.0.0").to_i
    => 1040187392
    >> high = IPAddr.new("62.255.255.255").to_i
    => 1056964607
    >> ip = IPAddr.new("62.156.244.13").to_i
    => 1050473485
    >> (low..high)===ip
    => true
    

    If you are given the network instead of the start and end addresses, it is even simpler

    >> net = IPAddr.new("62.0.0.0/8")
    => #
    >> net===IPAddr.new("62.156.244.13")
    => true
    

    IPAddr will also work with IPv6 addresses

    >> low = IPAddr.new('1::')
    => #
    >> high = IPAddr.new('2::')
    => #
    >> (low..high)===IPAddr.new('1::1')
    => true
    

提交回复
热议问题