Wildcard IP Banning with MySQL

前端 未结 5 1931
甜味超标
甜味超标 2021-02-01 11:01

I\'m trying to implement an IP banning system into my web app using MySQL, i know i can do it using .htaccess but that\'s not neat to me.

Basically my curre

5条回答
  •  野性不改
    2021-02-01 11:39

    This is trickier if you want to ban subnets

    Notes:

    • A "wildcard" mapping should use 0 (eg 42.21.58.0) which defines that subnet
    • the .0 may not be the subnet because of CIDR (could .128, .192 etc)

    So:

    • Store IP as a 4 byte binary or unsigned int
    • Store the subnet mask as a binary (or uint) 4 for subnet blacklisting
    • Look at INET_NTOA and INET_ATON for translating IP addresses

    Then the WHERE clause becomes

    WHERE ip = @ip   --whole IP
          OR
          (ip & mask = @ip) --subnet
    

    If you make the mask 0xffffffff for exact IP addresses then you can always do ip & mask = @ip, with ip & mask as a computed column

    Also, you have IPv6 to think of too

提交回复
热议问题