Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 712629
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 14, 20262026-05-14T04:52:10+00:00 2026-05-14T04:52:10+00:00

Writing an asynchronous Ping using Raw Sockets in F#, to enable parallel requests using

  • 0

Writing an asynchronous Ping using Raw Sockets in F#, to enable parallel requests using as few threads as possible. Not using “System.Net.NetworkInformation.Ping”, because it appears to allocate one thread per request. Am also interested in using F# async workflows.

The synchronous version below correctly times out when the target host does not exist/respond, but the asynchronous version hangs. Both work when the host does respond. Not sure if this is a .NET issue, or an F# one…

Any ideas?

(note: the process must run as Admin to allow Raw Socket access)

This throws a timeout:

let result = Ping.Ping ( IPAddress.Parse( "192.168.33.22" ), 1000 )

However, this hangs:

let result = Ping.AsyncPing ( IPAddress.Parse( "192.168.33.22" ), 1000 )
             |> Async.RunSynchronously

Here’s the code…

module Ping

open System
open System.Net
open System.Net.Sockets
open System.Threading

//---- ICMP Packet Classes

type IcmpMessage (t : byte) =
    let mutable m_type = t
    let mutable m_code = 0uy
    let mutable m_checksum = 0us

    member this.Type
        with get() = m_type

    member this.Code
        with get() = m_code

    member this.Checksum = m_checksum

    abstract Bytes : byte array

    default this.Bytes
        with get() =
            [|
                m_type
                m_code
                byte(m_checksum)
                byte(m_checksum >>> 8)
            |]

    member this.GetChecksum() =
        let mutable sum = 0ul
        let bytes = this.Bytes
        let mutable i = 0

        // Sum up uint16s
        while i < bytes.Length - 1 do
            sum <- sum + uint32(BitConverter.ToUInt16( bytes, i ))
            i <- i + 2

        // Add in last byte, if an odd size buffer
        if i <> bytes.Length then
            sum <- sum + uint32(bytes.[i])

        // Shuffle the bits
        sum <- (sum >>> 16) + (sum &&& 0xFFFFul)
        sum <- sum + (sum >>> 16)
        sum <- ~~~sum
        uint16(sum)

    member this.UpdateChecksum() =
        m_checksum <- this.GetChecksum()


type InformationMessage (t : byte) =
    inherit IcmpMessage(t)

    let mutable m_identifier = 0us
    let mutable m_sequenceNumber = 0us

    member this.Identifier = m_identifier
    member this.SequenceNumber = m_sequenceNumber

    override this.Bytes
        with get() =
            Array.append (base.Bytes)
                         [|
                            byte(m_identifier)
                            byte(m_identifier >>> 8)
                            byte(m_sequenceNumber)
                            byte(m_sequenceNumber >>> 8)
                         |]

type EchoMessage() =
    inherit InformationMessage( 8uy )
    let mutable m_data = Array.create 32 32uy
    do base.UpdateChecksum()

    member this.Data
        with get()  = m_data
        and  set(d) = m_data <- d
                      this.UpdateChecksum()

    override this.Bytes
        with get() =
            Array.append (base.Bytes)
                         (this.Data)

//---- Synchronous Ping

let Ping (host : IPAddress, timeout : int ) =
    let mutable ep = new IPEndPoint( host, 0 )
    let socket = new Socket( AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.Icmp )
    socket.SetSocketOption( SocketOptionLevel.Socket, SocketOptionName.SendTimeout, timeout )
    socket.SetSocketOption( SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, timeout )
    let packet = EchoMessage()
    let mutable buffer = packet.Bytes

    try
        if socket.SendTo( buffer, ep ) <= 0 then
            raise (SocketException())
        buffer <- Array.create (buffer.Length + 20) 0uy

        let mutable epr = ep :> EndPoint
        if socket.ReceiveFrom( buffer, &epr ) <= 0 then
            raise (SocketException())
    finally
        socket.Close()

    buffer

//---- Entensions to the F# Async class to allow up to 5 paramters (not just 3)

type Async with
    static member FromBeginEnd(arg1,arg2,arg3,arg4,beginAction,endAction,?cancelAction): Async<'T> =
        Async.FromBeginEnd((fun (iar,state) -> beginAction(arg1,arg2,arg3,arg4,iar,state)), endAction, ?cancelAction=cancelAction)
    static member FromBeginEnd(arg1,arg2,arg3,arg4,arg5,beginAction,endAction,?cancelAction): Async<'T> =
        Async.FromBeginEnd((fun (iar,state) -> beginAction(arg1,arg2,arg3,arg4,arg5,iar,state)), endAction, ?cancelAction=cancelAction)

//---- Extensions to the Socket class to provide async SendTo and ReceiveFrom

type System.Net.Sockets.Socket with

    member this.AsyncSendTo( buffer, offset, size, socketFlags, remoteEP ) =
        Async.FromBeginEnd( buffer, offset, size, socketFlags, remoteEP,
                            this.BeginSendTo,
                            this.EndSendTo )
    member this.AsyncReceiveFrom( buffer, offset, size, socketFlags, remoteEP ) =
        Async.FromBeginEnd( buffer, offset, size, socketFlags, remoteEP,
                            this.BeginReceiveFrom,
                            (fun asyncResult -> this.EndReceiveFrom(asyncResult, remoteEP) ) )

//---- Asynchronous Ping

let AsyncPing (host : IPAddress, timeout : int ) =  
    async {
        let ep = IPEndPoint( host, 0 )
        use socket = new Socket( AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.Icmp )
        socket.SetSocketOption( SocketOptionLevel.Socket, SocketOptionName.SendTimeout, timeout )
        socket.SetSocketOption( SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, timeout )

        let packet = EchoMessage()
        let outbuffer = packet.Bytes

        try
            let! result = socket.AsyncSendTo( outbuffer, 0, outbuffer.Length, SocketFlags.None, ep )
            if result <= 0 then
                raise (SocketException())

            let epr = ref (ep :> EndPoint)
            let inbuffer = Array.create (outbuffer.Length + 256) 0uy 
            let! result = socket.AsyncReceiveFrom( inbuffer, 0, inbuffer.Length, SocketFlags.None, epr )
            if result <= 0 then
                raise (SocketException())
            return inbuffer
        finally
            socket.Close()
    }
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-14T04:52:10+00:00Added an answer on May 14, 2026 at 4:52 am

    After some thought, came up with the following. This code adds an AsyncReceiveEx member to Socket, which includes a timeout value. It hides the details of the watchdog timer inside the receive method… very tidy and self contained. Now THIS is what I was looking for!

    See the complete async ping example, further below.

    Not sure if the locks are necessary, but better safe than sorry…

    type System.Net.Sockets.Socket with
        member this.AsyncSend( buffer, offset, size, socketFlags, err ) =
            Async.FromBeginEnd( buffer, offset, size, socketFlags, err,
                                this.BeginSend,
                                this.EndSend,
                                this.Close )
    
        member this.AsyncReceive( buffer, offset, size, socketFlags, err ) =
            Async.FromBeginEnd( buffer, offset, size, socketFlags, err,
                                this.BeginReceive,
                                this.EndReceive,
                                this.Close )
    
        member this.AsyncReceiveEx( buffer, offset, size, socketFlags, err, (timeoutMS:int) ) =
            async {
                let timedOut = ref false
                let completed = ref false
                let timer = new System.Timers.Timer( double(timeoutMS), AutoReset=false )
                timer.Elapsed.Add( fun _ ->
                    lock timedOut (fun () ->
                        timedOut := true
                        if not !completed
                        then this.Close()
                        )
                    )
                let complete() =
                    lock timedOut (fun () ->
                        timer.Stop()
                        timer.Dispose()
                        completed := true
                        )
                return! Async.FromBeginEnd( buffer, offset, size, socketFlags, err,
                                    (fun (b,o,s,sf,e,st,uo) ->
                                        let result = this.BeginReceive(b,o,s,sf,e,st,uo)
                                        timer.Start()
                                        result
                                    ),
                                    (fun result ->
                                        complete()
                                        if !timedOut
                                        then err := SocketError.TimedOut; 0
                                        else this.EndReceive( result, err )
                                    ),
                                    (fun () ->
                                        complete()
                                        this.Close()
                                        )
                                    )
                }
    

    Here is a complete Ping example. To avoid running out of source ports and to prevent getting too many replies at once, it scans one class-c subnet at a time.

    module Ping
    
    open System
    open System.Net
    open System.Net.Sockets
    open System.Threading
    
    //---- ICMP Packet Classes
    
    type IcmpMessage (t : byte) =
        let mutable m_type = t
        let mutable m_code = 0uy
        let mutable m_checksum = 0us
    
        member this.Type
            with get() = m_type
    
        member this.Code
            with get() = m_code
    
        member this.Checksum = m_checksum
    
        abstract Bytes : byte array
    
        default this.Bytes
            with get() =
                [|
                    m_type
                    m_code
                    byte(m_checksum)
                    byte(m_checksum >>> 8)
                |]
    
        member this.GetChecksum() =
            let mutable sum = 0ul
            let bytes = this.Bytes
            let mutable i = 0
    
            // Sum up uint16s
            while i < bytes.Length - 1 do
                sum <- sum + uint32(BitConverter.ToUInt16( bytes, i ))
                i <- i + 2
    
            // Add in last byte, if an odd size buffer
            if i <> bytes.Length then
                sum <- sum + uint32(bytes.[i])
    
            // Shuffle the bits
            sum <- (sum >>> 16) + (sum &&& 0xFFFFul)
            sum <- sum + (sum >>> 16)
            sum <- ~~~sum
            uint16(sum)
    
        member this.UpdateChecksum() =
            m_checksum <- this.GetChecksum()
    
    
    type InformationMessage (t : byte) =
        inherit IcmpMessage(t)
    
        let mutable m_identifier = 0us
        let mutable m_sequenceNumber = 0us
    
        member this.Identifier = m_identifier
        member this.SequenceNumber = m_sequenceNumber
    
        override this.Bytes
            with get() =
                Array.append (base.Bytes)
                             [|
                                byte(m_identifier)
                                byte(m_identifier >>> 8)
                                byte(m_sequenceNumber)
                                byte(m_sequenceNumber >>> 8)
                             |]
    
    type EchoMessage() =
        inherit InformationMessage( 8uy )
        let mutable m_data = Array.create 32 32uy
        do base.UpdateChecksum()
    
        member this.Data
            with get()  = m_data
            and  set(d) = m_data <- d
                          this.UpdateChecksum()
    
        override this.Bytes
            with get() =
                Array.append (base.Bytes)
                             (this.Data)
    
    //---- Entensions to the F# Async class to allow up to 5 paramters (not just 3)
    
    type Async with
        static member FromBeginEnd(arg1,arg2,arg3,arg4,beginAction,endAction,?cancelAction): Async<'T> =
            Async.FromBeginEnd((fun (iar,state) -> beginAction(arg1,arg2,arg3,arg4,iar,state)), endAction, ?cancelAction=cancelAction)
        static member FromBeginEnd(arg1,arg2,arg3,arg4,arg5,beginAction,endAction,?cancelAction): Async<'T> =
            Async.FromBeginEnd((fun (iar,state) -> beginAction(arg1,arg2,arg3,arg4,arg5,iar,state)), endAction, ?cancelAction=cancelAction)
    
    //---- Extensions to the Socket class to provide async SendTo and ReceiveFrom
    
    type System.Net.Sockets.Socket with
    
        member this.AsyncSend( buffer, offset, size, socketFlags, err ) =
            Async.FromBeginEnd( buffer, offset, size, socketFlags, err,
                                this.BeginSend,
                                this.EndSend,
                                this.Close )
    
        member this.AsyncReceive( buffer, offset, size, socketFlags, err ) =
            Async.FromBeginEnd( buffer, offset, size, socketFlags, err,
                                this.BeginReceive,
                                this.EndReceive,
                                this.Close )
    
        member this.AsyncReceiveEx( buffer, offset, size, socketFlags, err, (timeoutMS:int) ) =
            async {
                let timedOut = ref false
                let completed = ref false
                let timer = new System.Timers.Timer( double(timeoutMS), AutoReset=false )
                timer.Elapsed.Add( fun _ ->
                    lock timedOut (fun () ->
                        timedOut := true
                        if not !completed
                        then this.Close()
                        )
                    )
                let complete() =
                    lock timedOut (fun () ->
                        timer.Stop()
                        timer.Dispose()
                        completed := true
                        )
                return! Async.FromBeginEnd( buffer, offset, size, socketFlags, err,
                                    (fun (b,o,s,sf,e,st,uo) ->
                                        let result = this.BeginReceive(b,o,s,sf,e,st,uo)
                                        timer.Start()
                                        result
                                    ),
                                    (fun result ->
                                        complete()
                                        if !timedOut
                                        then err := SocketError.TimedOut; 0
                                        else this.EndReceive( result, err )
                                    ),
                                    (fun () ->
                                        complete()
                                        this.Close()
                                        )
                                    )
                }
    
    //---- Asynchronous Ping
    
    let AsyncPing (ip : IPAddress, timeout : int ) =  
        async {
            use socket = new Socket( AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.Icmp )
            socket.Connect( IPEndPoint( ip, 0 ) )
    
            let pingTime = System.Diagnostics.Stopwatch()
            let packet = EchoMessage()
            let outbuffer = packet.Bytes
            let err = ref (SocketError())
    
            let isAlive = ref false
            try
                pingTime.Start()
                let! result = socket.AsyncSend( outbuffer, 0, outbuffer.Length, SocketFlags.None, err )
                pingTime.Stop()
    
                if result <= 0 then
                    raise (SocketException(int(!err)))
    
                let inbuffer = Array.create (outbuffer.Length + 256) 0uy 
    
                pingTime.Start()
                let! reply = socket.AsyncReceiveEx( inbuffer, 0, inbuffer.Length, SocketFlags.None, err, timeout )
                pingTime.Stop()
    
                if result <= 0 && not (!err = SocketError.TimedOut) then
                    raise (SocketException(int(!err)))
    
                isAlive := not (!err = SocketError.TimedOut)
                              && inbuffer.[25] = 0uy // Type 0 = echo reply (redundent? necessary?)
                              && inbuffer.[26] = 0uy // Code 0 = echo reply (redundent? necessary?)
            finally
                socket.Close()
    
            return (ip, pingTime.Elapsed, !isAlive )
        }
    
    let main() =
        let pings net =
            seq {
                for node in 0..255 do
                    let ip = IPAddress.Parse( sprintf "192.168.%d.%d" net node )
                    yield Ping.AsyncPing( ip, 1000 )
                }
    
        for net in 0..255 do
            pings net
            |> Async.Parallel
            |> Async.RunSynchronously
            |> Seq.filter ( fun (_,_,alive) -> alive )
            |> Seq.iter ( fun (ip, time, alive) ->
                              printfn "%A %dms" ip time.Milliseconds)
    
    main()
    System.Console.ReadKey() |> ignore
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I was writing an asynchronous logging framework, where I had multiple threads dumping data.
greetings, i am writng a socket program using sockets in c# (asynchronous). the issue
I'm writing an event driven application using the libevent library for asynchronous I/O. Essentially,
I'm writing some code with boost::asio , using asynchronous TCP connections. I've to admit
I am writing a web-connected application that needs to execute several asynchronous requests to
Background I'm writing an asynchronous comment system for my website, after reading plenty of
Writing a python program, and I came up with this error while using the
Writing a .NET DLL how do I find Application.ProductName ? EDIT: Obviously, importing Windows.Forms
Writing my first C# application...never touched the language before and not much of a
I'm writing an asynchronous image downloader for Android and was just wondering, given an

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.