Use the external cidr_match library.

  This simplifies the logic considerably.