added proper condition on the upper boundary (end_ip)

This is mostly an extension of a pull request by Otavio Garcia, but
in all the places that need it, and also adding relevant tests.