Here you for every port try to find free from range beginning. You can save last allocated port for ip in some structure and use it for next port allocation. There is similar logic in ipallocator now.
Also it's immediatly will give you another port in your `goto` block.