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

前端 未结 6 2321
礼貌的吻别
礼貌的吻别 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:25

    Your code compares strings, not numbers. I would suggest using tuples instead:

    >>> ip_range = [(1,1,0,0), (1,1,255,255)]
    >>> testip = (1,1,2,2)
    >>> testip > ip_range[0] and testip < ip_range[1]
    True
    >>> testip = (1,3,1,1)
    >>> testip > ip_range[0] and testip < ip_range[1]
    False
    

提交回复
热议问题