It might be worth replacing `ip` with something a bit clearer here.  Not your fault, I know, but I had real trouble reading that code and knowing if this was actually correct because of the short variable names.