Skip to content

Instantly share code, notes, and snippets.

@spencerwi
Created January 9, 2017 12:11
Show Gist options
  • Save spencerwi/1aed179443e1ffc42b84176ef1c34209 to your computer and use it in GitHub Desktop.
Save spencerwi/1aed179443e1ffc42b84176ef1c34209 to your computer and use it in GitHub Desktop.
Get IP addresses on local machine (using only F# stdlib)
open System
open System.Net
open System.Linq
let applyFilters showIPv4Only showIPv6Only addrs =
match (showIPv4Only, showIPv6Only) with
| (true, false) -> Seq.filter (fun (addr: IPAddress) -> addr.AddressFamily = Sockets.AddressFamily.InterNetwork) addrs
| (false, true) -> Seq.filter (fun (addr: IPAddress) -> addr.AddressFamily = Sockets.AddressFamily.InterNetworkV6) addrs
| (_, _) -> addrs
type CLIArgs = {
ipv4Only: bool;
ipv6Only: bool;
}
let parse_args args : CLIArgs =
let ipv4Only = Array.contains "-4" args in
let ipv6Only = Array.contains "-6" args in
{ipv4Only = ipv4Only; ipv6Only = ipv6Only}
let () =
let args = parse_args (System.Environment.GetCommandLineArgs()) in
NetworkInformation.NetworkInterface.GetAllNetworkInterfaces()
|> Array.toSeq
|> Seq.filter (fun iface -> iface.NetworkInterfaceType <> NetworkInformation.NetworkInterfaceType.Loopback)
|> Seq.map (fun x -> x.GetIPProperties())
|> Seq.collect (fun x -> x.UnicastAddresses)
|> Seq.map (fun addrObj -> addrObj.Address)
|> (applyFilters args.ipv4Only args.ipv6Only)
|> Seq.iter (printfn "%A")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment