findUnusedPort function

Future<int> findUnusedPort()

Returns a port that is probably, but not definitely, not in use.

This has a built-in race condition: another process may bind this port at any time after this call has returned.

Implementation

Future<int> findUnusedPort() async {
  int port;
  ServerSocket socket;
  try {
    socket =
        await ServerSocket.bind(InternetAddress.loopbackIPv6, 0, v6Only: true);
  } on SocketException {
    socket = await ServerSocket.bind(InternetAddress.loopbackIPv4, 0);
  }
  port = socket.port;
  await socket.close();
  return port;
}