Forum Discussion

Ashish_Gupta_15's avatar
Ashish_Gupta_15
Icon for Nimbostratus rankNimbostratus
Dec 07, 2016

Detect IP in a range in iRule

For the IPs in a range for example 91.186.192.0 to 91.186.223.255, how should I structure the datagroup list to detect if the incoming IP is within the that range using the iRule.

 

There are many IP ranges. If I calculate the CIDR for each range beforehand (an example CIDR for the above range would be 91.186.192.0/19), can I make use of the CIDR to delect if the incoming IP is within the given range using iRule?

 

  • Hi Ashish,

    F5s

    [IP::addr]
    or F5s
    [class]
    command in combination with an IP-ADDR based data-group can be used can be used to check if a given IP address falls in the range of a given
    /CIDR
    subnet.

    The

    [IP::addr]
    command is useful if you need to compare just a few different subnets...

    if { [IP::addr [IP::client_addr] equals 91.186.192.0/19] } then {
        log local0.debug "The IP matches 91.186.192.0/19"
    } elseif { [IP::addr [IP::client_addr] equals 91.186.224.0/19] } then {
        log local0.debug "The IP matches 91.186.224.0/19"
    } elseif { [IP::addr [IP::client_addr] equals 91.186.0.0/16] } then {
        log local0.debug "The IP matches 91.186.0.0/16"
    } else { 
        log local0.debug "The IP matches none of the subnets"
    }
    

    Note: The order of the

    [if]
    statement is important for overlapping subnets. The check is always performed as "first-match".

    Whereas the

    [class]
    command scales much better if you need to compare multiple subnets...

    iRule:

    if { [set result [class lookup -value [IP::client_addr] equals DG_MY_SUBNETS]] ne "" } then {
        log local0.debug $result
    }
    

    Data-Group:

    ltm data-group internal DG_MY_SUBNETS {
        records {
            91.186.192.0/19 {
                data "The IP matches 91.186.192.0/19"
            }
            91.186.224.0/19 {
                data "The IP matches 91.186.224.0/19"
            }
            91.186.0.0/16 {
                data "The IP matches 91.186.0.0/16"
            }
            0.0.0.0/0 {
                data "The IP matches none of the subnets"
            }
        }
        type ip
    }
    

    Note: The order of the data-group does not matter. The check is always performed as "best-match"

    Cheers, Kai