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?
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.
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.
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;
});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With