Skip to content

Instantly share code, notes, and snippets.

@vhogemann
Last active November 15, 2023 12:03
Show Gist options
  • Save vhogemann/4ea9fd81748fb765b07c5bcdb3c736cb to your computer and use it in GitHub Desktop.
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#
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