check if an IP is within a range of CIDR in Python

前端 未结 6 2359
礼貌的吻别
礼貌的吻别 2021-01-05 15:55

I know there are some similar questions up here, but they mostly either want to find the range itself (which uses some libraries, like the example that stackoverflow says is

6条回答
  •  一向
    一向 (楼主)
    2021-01-05 16:14

    This doesn't work in general, because string comparison is in collating order, not the numerical values of the four fields. For instance, '1.1.2.2' > '1.1.128.1' -- the critical spot in the 5th character, '1' vs '2'.

    If you want to compare the fields, try separating into lists:

    ip_vals = [int(x) for x in ip_range.split('.')]
    

    ip_vals is now a list of the values; you can compare the lists and get the results I think you want.

提交回复
热议问题