How can I find an unused TCP port in Dart?

dart

Solution

I'll add my 'hack' as an answer because I can't think of another way, and it seems to work pretty well.

Here's my `getUnusedPort()` function:

import 'dart:io';

Future<int> getUnusedPort(InternetAddress address) {
  return ServerSocket.bind(address ?? InternetAddress.anyIPv4, 0).then((socket) {
    var port = socket.port;
    socket.close();
    return port;
  });
}

Problem

I'm trying to launch a process and tell it to use an unused TCP port. Unfortunately, the binary I'm starting won't probe for an unused port. Is there a decent way for me to probe ports in Dart so I can use that as an argument to my process? The best I can think of is to create a `ServerSocket` with a port of 0, and then close the socket and use it's port, but this seems hacky to me. Anyone have a better way?

Original source