Try this..
_conn {
sockclose _conn
sockclose open
var %port = 1
; If you don't want the port range to start at 1, then change 1 to a higher number.
while (!$portfree(%port)) && (%port < 65536) inc %port
socklisten Open %port
.server 127.0.0.1 %port
if (!$timer(_dc)) .timer_dc 0 69 /_dc
}
This should always find a free port, unless every single one of your ports is in use, which is highly unlikely if it's even possible.
I also changed the first two lines because mIRC's /sockclose command has built-in error checking, so you don't need to check if ($sock(_conn)) before attempting to /sockclose it.