Last active
November 15, 2023 12:03
-
-
Save vhogemann/4ea9fd81748fb765b07c5bcdb3c736cb to your computer and use it in GitHub Desktop.
Quick and dirty example of how to get a random open TCP/UDP port using F#
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
namespace Test | |
module RandomPort = | |
open System | |
open System.Net.NetworkInformation | |
let isFree port = | |
let props = | |
IPGlobalProperties.GetIPGlobalProperties() | |
let tcpListeners = | |
props.GetActiveTcpListeners() | |
|> Array.map (fun it -> it.Port) | |
|> List.ofArray | |
let udpListeners = | |
props.GetActiveUdpListeners() | |
|> Array.map (fun it -> it.Port) | |
|> List.ofArray | |
tcpListeners @ udpListeners | |
|> List.forall (fun it -> it <> port) | |
let next () = | |
let rnd = Random() | |
seq { yield rnd.Next(1, 65535) } | |
|> Seq.find isFree |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment