Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I find an unused TCP port in Dart?

Tags:

dart

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?

like image 621
Justin Fagnani Avatar asked Dec 30 '12 18:12

Justin Fagnani


People also ask

How do I find unused TCP ports?

You can use "netstat" to check whether a port is available or not. Use the netstat -anp | find "port number" command to find whether a port is occupied by an another process or not. If it is occupied by an another process, it will show the process id of that process.

How do I find out what ports are available?

Run the Command Prompt as administrator. Type the command: netstat -ab and hit Enter. Wait for the results to load. Port names will be listed next to the local IP address.


1 Answers

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;
  });
}
like image 175
Justin Fagnani Avatar answered Oct 19 '22 15:10

Justin Fagnani