# FreeRTOS IP callbacks

**URL:** <https://forums.freertos.org/t/freertos-ip-callbacks/7786>\
**Category:** Kernel\
**Created:** [April 15, 2019, 8:52am UTC](https://forums.freertos.org/t/freertos-ip-callbacks/7786 "2019-04-15T08:52:40Z")\
**Posts on this page:** 18\
**Page:** 1

<div class="post-metadata">

**Author:** ![system](https://d2v6vdsk2p900z.cloudfront.net/original/1X/7fc8fdb729c645aab5b20282bbe34e57cb407be6.jpeg) [@system](https://forums.freertos.org/u/system)\
**Post date:** [April 15, 2019, 8:52am UTC](https://forums.freertos.org/t/freertos-ip-callbacks/7786/1 "2019-04-15T08:52:40Z")

</div>

**[eduardo1966](https://sourceforge.net/u/eduardo1966/)** wrote on [Monday, April 15, 2019](https://sourceforge.net/p/freertos/discussion/382005/thread/b3ece8be94/#47ac):

Hi

I’ve written some code (see below) that implements a connect/disconnet/receiver using IP sockets and callback functions.  
Somehow this ends in the Dummy\_Handler()…

Essentialy a socket is created, a callback function is associated with this socket to process events Connect and Disconnect.  
When a connect happens an accept is called and a receiving socket is created and associated with another callback function.  
When a disconnect happens the receiving socket is closed.  
When data arrives some information is printed.  
ALl the communication between the callback functions and the main task is done through a message Queue.

Could someone validate this code? It may happen that the code is not using the FreeRTOS IP functions correctly…  
I’ve placed several breakpoints and I cannot figure out what makes the code crash.

```auto

static void Callback_OnConnectDisconnect ( Socket_t xSocket, BaseType_t ulConnected )
{
    Callback_Message_t Callback_Message;

    Callback_Message.type = Callback_Connect_Disconnect;
    Callback_Message.Connect_Disconnect.xSocket = xSocket;
    Callback_Message.Connect_Disconnect.ulConnected = ulConnected;

    if ( xQueueSend ( xQueue_Callback, (void*) &Callback_Message, 0 ) != pdPASS )
        /* In case there is no space in the Queue,
         * we should print something to the service port but we are inside FreeRTOS IP so it's better just increment a counter.
         * The printing will take place in the main loop.
         */
        xQueue_Callback_Errors++;
}

static BaseType_t Callback_OnReceive ( Socket_t xSocket, void * pData, size_t xLength )
{
    Callback_Message_t Callback_Message;

    Callback_Message.type = Callback_Receive;
    Callback_Message.Receive.xSocket = xSocket;
    Callback_Message.Receive.pData = pData;
    Callback_Message.Receive.xLength = xLength;

    if ( xQueueSend ( xQueue_Callback, (void*) &Callback_Message, 0 ) != pdPASS )
        /* In case there is no space in the Queue,
         * we should print something to the service port but we are inside FreeRTOS IP so it's better just increment a counter.
         * The printing will take place in the main loop.
         */
        xQueue_Callback_Errors++;

    return 1;
}

void task_IPreceiver ( void *pvParameters )
{
    Socket_t IPaccept_Socket, IPreceiver_Socket;
    struct freertos_sockaddr xClient, xBindAddress;
    const TickType_t xTimeOut = pdMS_TO_TICKS( 2000 );
    const TickType_t xZeroTimeOut = 0;
    socklen_t xSize = sizeof (struct freertos_sockaddr);
    F_TCP_UDP_Handler_t Handler_OnConnectDisconnect;

    SP_Printf ( "task_IPreceiver[] running..." );

    /* Create a queue capable of containing 10 callback messages. */
    xQueue_Callback = xQueueCreate ( 10, sizeof(Callback_Message_t) );

    IPaccept_Socket = FreeRTOS_socket ( FREERTOS_AF_INET, FREERTOS_SOCK_STREAM, FREERTOS_IPPROTO_TCP );
    if ( IPaccept_Socket == NULL )
        SP_Printf_h ( "ERROR - task_IPaccept[] - FreeRTOS_socket failed" );

    xBindAddress.sin_port = FreeRTOS_htons ( VDUI_SERVER_PORT );

    FreeRTOS_bind ( IPaccept_Socket, &xBindAddress, sizeof(xBindAddress) );

    FreeRTOS_listen ( IPaccept_Socket, IP_MAX_CONNECTIONS );

    /* Install a callback for connection and disconnection events. */
    Handler_OnConnectDisconnect.pxOnTCPConnected = Callback_OnConnectDisconnect;
    FreeRTOS_setsockopt ( IPaccept_Socket, 0, FREERTOS_SO_TCP_CONN_HANDLER, (void *) &Handler_OnConnectDisconnect, sizeof(Handler_OnConnectDisconnect) );

    //IPconnections_Initialise();

    for (;;)
    {
        Callback_Message_t Callback_Message;

        if ( xQueue_Callback_Errors != xQueue_Callback_Errors_prev )
        {
            SP_Printf ( "WARNING - task_IPreceiver[] - xQueue_Callback_Errors %d", xQueue_Callback_Errors );
            xQueue_Callback_Errors_prev = xQueue_Callback_Errors;
        }

        if ( xQueueReceive ( xQueue_Callback, &Callback_Message, portMAX_DELAY ) )
        {
            switch ( Callback_Message.type )
            {
                case Callback_Connect_Disconnect:
                {
                    F_TCP_UDP_Handler_t Handler_OnReceive;

                    if ( Callback_Message.Connect_Disconnect.ulConnected )
                    {
                        IPreceiver_Socket = FreeRTOS_accept ( IPaccept_Socket, &xClient, &xSize );

                        SP_Printf ( "Connection accepted %d", IPreceiver_Socket );

                        /* Install a callback for receiving TCP data. */
                        Handler_OnConnectDisconnect.pxOnTCPReceive = Callback_OnReceive;
                        FreeRTOS_setsockopt ( IPreceiver_Socket, 0, FREERTOS_SO_TCP_RECV_HANDLER, (void *) &Handler_OnReceive, sizeof(Handler_OnReceive) );
                    }
                    else
                    {
                        FreeRTOS_shutdown ( Callback_Message.Connect_Disconnect.xSocket, FREERTOS_SHUT_RDWR );
                        FreeRTOS_closesocket ( Callback_Message.Connect_Disconnect.xSocket );

                        SP_Printf ( "Connection closed %d", Callback_Message.Connect_Disconnect.xSocket );
                    }
                }break;

                case Callback_Receive:
                {
                    static uint8_t Data [1000];
                    int32_t receivedData;

                    receivedData = FreeRTOS_recv ( Callback_Message.Receive.xSocket, Data/*pvBuffer*/, sizeof(Data)/*xBufferLength*/, 0/*xFlags*/ );

                    SP_Printf ( "Callback_Receive Callback_Message.Receive.xSocket %d Callback_Message.Receive.xLength %d receivedData %d",
                                        Callback_Message.Receive.xSocket, Callback_Message.Receive.xLength, receivedData );
                }break;
            }
        }
    }
}

```

---

<div class="post-metadata">

**Author:** ![htibosch](https://d3iykfbgfh8zhg.cloudfront.net/user_avatar/forums.freertos.org/htibosch/32/62_2.png) [@htibosch](https://forums.freertos.org/u/htibosch)\
**Post date:** [April 15, 2019, 9:21am UTC](https://forums.freertos.org/t/freertos-ip-callbacks/7786/2 "2019-04-15T09:21:08Z")

</div>

**[heinbali01](https://sourceforge.net/u/heinbali01/)** wrote on [Monday, April 15, 2019](https://sourceforge.net/p/freertos/discussion/382005/thread/b3ece8be94/#09b9):

The code looks perfect to me. It is an original approach!

Isn’t the `Dummy_Handler()` called as a default handler, in case no other exception handler is defined?

The problem might be unrelated to the code that you show here. Maybe it is an interrupt from a peripheral that you forgot to implement?

Well, one remark regarding the code:

```auto
	FreeRTOS_shutdown ( Callback_Message.Connect_Disconnect.xSocket, FREERTOS_SHUT_RDWR );
	FreeRTOS_closesocket ( Callback_Message.Connect_Disconnect.xSocket );

```

Here a disconnect was detected, and therefore it makes no sense to call `FreeRTOS_shutdown()`. It is enough to close the socket. This is unrelated to the crash though.

---

<div class="post-metadata">

**Author:** ![htibosch](https://d3iykfbgfh8zhg.cloudfront.net/user_avatar/forums.freertos.org/htibosch/32/62_2.png) [@htibosch](https://forums.freertos.org/u/htibosch)\
**Post date:** [April 15, 2019, 9:27am UTC](https://forums.freertos.org/t/freertos-ip-callbacks/7786/3 "2019-04-15T09:27:29Z")

</div>

**[heinbali01](https://sourceforge.net/u/heinbali01/)** wrote on [Monday, April 15, 2019](https://sourceforge.net/p/freertos/discussion/382005/thread/b3ece8be94/#b7a2):

In case you’re interest in using `FreeRTOS_shutdown()`. Here is an example where it is useful, e.g. to initiate a graceful close of a TCP connection:

[+TCP - How force a close on a TCP connection on a Remote Server](https://sourceforge.net/p/freertos/discussion/382005/thread/794f3d82/?limit=25#619b)

And here is a more complicated example: data is still being sent while the closure has been initiated:

[FreeRTOS\_recv returns pdFREERTOS\_ERRNO\_ENOTCONN but also all the data](https://sourceforge.net/p/freertos/discussion/382005/thread/fe2c5dd342/?limit=250#cfad)

---

<div class="post-metadata">

**Author:** ![system](https://d2v6vdsk2p900z.cloudfront.net/original/1X/7fc8fdb729c645aab5b20282bbe34e57cb407be6.jpeg) [@system](https://forums.freertos.org/u/system)\
**Post date:** [April 15, 2019, 9:42am UTC](https://forums.freertos.org/t/freertos-ip-callbacks/7786/4 "2019-04-15T09:42:22Z")

</div>

**[eduardo1966](https://sourceforge.net/u/eduardo1966/)** wrote on [Monday, April 15, 2019](https://sourceforge.net/p/freertos/discussion/382005/thread/b3ece8be94/#ee1d):

thanks for the answer.  
I would prefered to have used semaphores.  
As you suggested in this thread:  
[https://sourceforge.net/p/freertos/discussion/382005/thread/cc5add6c85/?limit=25](https://sourceforge.net/p/freertos/discussion/382005/thread/cc5add6c85/?limit=25)  
But I coudn’t figure out after Take the semaphore which functions to call to find the reason for the Give on the semaphore.

- A connection is established ( either accept() or connect() )
- A connection is broken ( or an error occurred )
- Data has arrived

I don’t think there are any other interrupts happening!  
The default handler for interrupts in the Dummy\_Handler() as defined in startup\_same70.c. I think I can find in some registers info about what generated the crash. I’ll investigate…

---

<div class="post-metadata">

**Author:** ![system](https://d2v6vdsk2p900z.cloudfront.net/original/1X/7fc8fdb729c645aab5b20282bbe34e57cb407be6.jpeg) [@system](https://forums.freertos.org/u/system)\
**Post date:** [April 15, 2019, 11:59am UTC](https://forums.freertos.org/t/freertos-ip-callbacks/7786/5 "2019-04-15T11:59:39Z")

</div>

**[eduardo1966](https://sourceforge.net/u/eduardo1966/)** wrote on [Monday, April 15, 2019](https://sourceforge.net/p/freertos/discussion/382005/thread/b3ece8be94/#fcdd):

I found where it crashes:  
FreeRTOS\_Sockets.c, version FreeRTOS+TCP V2.0.7 line 3021,

pxSocket-\>u.xTCP.pxHandleReceive( (Socket\_t _)pxSocket, ( void_ )ucReadPtr, ( size\_t ) ulCount );

pxHandleReceive has the impossible value of 0xA5A5A5A5, which must be stack related since the stack is filled with 0xA5s…  
(See attachment, please.)

Any ideas? Thanks.

---

<div class="post-metadata">

**Author:** ![system](https://d2v6vdsk2p900z.cloudfront.net/original/1X/7fc8fdb729c645aab5b20282bbe34e57cb407be6.jpeg) [@system](https://forums.freertos.org/u/system)\
**Post date:** [April 15, 2019, 12:47pm UTC](https://forums.freertos.org/t/freertos-ip-callbacks/7786/6 "2019-04-15T12:47:03Z")

</div>

**[eduardo1966](https://sourceforge.net/u/eduardo1966/)** wrote on [Monday, April 15, 2019](https://sourceforge.net/p/freertos/discussion/382005/thread/b3ece8be94/#61f8):

Ah bugs… 🙂  
**Handler\_OnConnectDisconnect**.pxOnTCPReceive = Callback\_OnReceive;  
should be instead:  
**Handler\_OnReceive**.pxOnTCPReceive = Callback\_OnReceive;

---

<div class="post-metadata">

**Author:** ![htibosch](https://d3iykfbgfh8zhg.cloudfront.net/user_avatar/forums.freertos.org/htibosch/32/62_2.png) [@htibosch](https://forums.freertos.org/u/htibosch)\
**Post date:** [April 15, 2019, 1:57pm UTC](https://forums.freertos.org/t/freertos-ip-callbacks/7786/7 "2019-04-15T13:57:26Z")

</div>

**[heinbali01](https://sourceforge.net/u/heinbali01/)** wrote on [Monday, April 15, 2019](https://sourceforge.net/p/freertos/discussion/382005/thread/b3ece8be94/#3309):

A copy & paste error 🙂

> I would preferred to have used semaphores.

When using semaphores, you would have to check all sockets that are owned by the task. I would embed each socket in an object that describes exactly the current status.

If you look at the FTP/HTTP server on [freertos/tcp](https://www.freertos.org/FreeRTOS-Labs/downloads/160919_FreeRTOS_Labs.zip?dl=0), it will become clear what I mean.

The status can be:

- Wait for connect
- Receiving a file
- Sending a file
- Idle state, waiting for a new command
- Waiting for a closure

---

<div class="post-metadata">

**Author:** ![system](https://d2v6vdsk2p900z.cloudfront.net/original/1X/7fc8fdb729c645aab5b20282bbe34e57cb407be6.jpeg) [@system](https://forums.freertos.org/u/system)\
**Post date:** [April 15, 2019, 2:27pm UTC](https://forums.freertos.org/t/freertos-ip-callbacks/7786/8 "2019-04-15T14:27:42Z")

</div>

**[eduardo1966](https://sourceforge.net/u/eduardo1966/)** wrote on [Monday, April 15, 2019](https://sourceforge.net/p/freertos/discussion/382005/thread/b3ece8be94/#c2b1):

thanks for the answer

I cannot find that example!  
The only place that I cand find using **FREERTOS\_SO\_SET\_SEMAPHORE** is:  
160919\_FreeRTOS\_Labs/FreeRTOS-Plus/Source/FreeRTOS-Plus-TCP/protocols/NTP/NTPDemo.c

Nevertheless, now that thye callbacks are almost working maybe I’ll stick with them 🙂  
I still have a problem which may be the result of my misunderstanding.

This is the callback for Receiving:

```auto
static BaseType_t Callback_OnReceive ( Socket_t xSocket, void * pData, size_t xLength )
{
    Callback_Message_t Callback_Message;

    Callback_Message.type = Callback_Receive;
    Callback_Message.Receive.xSocket = xSocket;
    Callback_Message.Receive.pData = pData;
    Callback_Message.Receive.xLength = xLength;

    if ( xQueueSend ( xQueue_Callback, (void*) &Callback_Message, 0 ) != pdPASS )
        /* In case there is no space in the Queue,
         * we should print something to the service port but we are inside FreeRTOS IP so it's better just increment a counter.
         * The printing will take place in the main loop.
         */
        xQueue_Callback_Errors++;

    return 1;
}

```

I just put the pointer for the data and the size of the data into a message queue.  
On the main task then:

```auto
                case Callback_Receive:
                {
                    static uint8_t Data [1000];
                    int32_t receivedData;

                    receivedData = FreeRTOS_recv ( Callback_Message.Receive.xSocket, Data/*pvBuffer*/, sizeof(Data)/*xBufferLength*/, 0/*xFlags*/ );

                    if ( receivedData == FREERTOS_ECLOSED )
                        SP_Printf ( "Socket %d is not connected", Callback_Message.Receive.xSocket );
                    else
                        SP_Printf ( "Callback_Receive Callback_Message.Receive.xSocket %d Callback_Message.Receive.xLength %d receivedData %d",
                                        Callback_Message.Receive.xSocket, Callback_Message.Receive.xLength, receivedData );
                }break;

```

I call FreeRTOS\_recv to get the data out. Is this correct? I can only see receivedData with -128 (connection closed) or 0 (zero bytes).

Should I retrieve the data inside the callback?  
That would mean allocating a buffer of the size of the message, copy the data and free it after processing… Is this the right approach?

How does FreeRTOS IP know that the data received has been used and therefor can be discarded?

thanks

---

<div class="post-metadata">

**Author:** ![htibosch](https://d3iykfbgfh8zhg.cloudfront.net/user_avatar/forums.freertos.org/htibosch/32/62_2.png) [@htibosch](https://forums.freertos.org/u/htibosch)\
**Post date:** [April 15, 2019, 4:01pm UTC](https://forums.freertos.org/t/freertos-ip-callbacks/7786/9 "2019-04-15T16:01:44Z")

</div>

**[heinbali01](https://sourceforge.net/u/heinbali01/)** wrote on [Monday, April 15, 2019](https://sourceforge.net/p/freertos/discussion/382005/thread/b3ece8be94/#a9cb):

> I cannot find that example!

Sorry, you’re right: the example doesn’t use a semaphore but `FreeRTOS_select()`. The implementation is the same however: every socket is embedded in a structure that stores the status of the connection. All sockets are checked in every loop.

> 160919\_FreeRTOS\_Labs

Please note that the +TCP sources in that distribution are very old. It is still there because of the old demo’s that used +FAT, and the FTP/HTTP servers.

The latest release of +FAT can be found on the [/labs download page](https://freertos.org/FreeRTOS-Labs/downloads/FreeRTOS-Plus-FAT-160919a-MIT.zip?dl=0). +TCP can be found on e.g. [github/aws](https://github.com/aws/amazon-freertos/)

> This is the callback for Receiving:
> 
> `static BaseType_t Callback_OnReceive ( Socket_t xSocket, void * pData, size_t xLength )`  
> `{`  
> `Callback_Message_t Callback_Message;`  
> `Callback_Message.type = Callback_Receive;`  
> `Callback_Message.Receive.xSocket = xSocket;`  
> `Callback_Message.Receive.pData = pData;`  
> `Callback_Message.Receive.xLength = xLength;`

Oops: the pointer `pData` will become invalid after the function returns. So you only access it from within this function.

> I call FreeRTOS\_recv to get the data out. Is this correct?

Yes that is OK.

> I can only see receivedData with -128 (connection closed) or 0 (zero bytes).

The data were flushed ( not stored ) because your function `Callback_OnReceive()` returned a positive value. When it returns zero, the data will be stored in the RX stream buffer of the socket.

> Should I retrieve the data inside the callback?

No let the socket store it and you retrieve it later.

> How does FreeRTOS IP know that the data received has been used and therefore can be discarded?

So yes, it looks at the return value: 1 = data consumed, 0 = please store data

> if ( receivedData == FREERTOS\_ECLOSED )

Note that there are two error codes that are not fatal: `-pdFREERTOS_ERRNO_EAGAIN` and `-pdFREERTOS_ERRNO_EINTR`. All other negative values must be treated in the same way as `-pdFREERTOS_ERRNO_ENOTCONN`: call `closesocket()`.

---

<div class="post-metadata">

**Author:** ![system](https://d2v6vdsk2p900z.cloudfront.net/original/1X/7fc8fdb729c645aab5b20282bbe34e57cb407be6.jpeg) [@system](https://forums.freertos.org/u/system)\
**Post date:** [April 15, 2019, 4:14pm UTC](https://forums.freertos.org/t/freertos-ip-callbacks/7786/10 "2019-04-15T16:14:08Z")

</div>

**[eduardo1966](https://sourceforge.net/u/eduardo1966/)** wrote on [Monday, April 15, 2019](https://sourceforge.net/p/freertos/discussion/382005/thread/b3ece8be94/#4515):

I had some feeling about the return 1; on the callback function.  
So I followed the code after returning and in fact on the file:

FreeRTOS\_Sockets.c, version V2.0.7, line 3021

```auto
						pxSocket->u.xTCP.pxHandleReceive( (Socket_t *)pxSocket, ( void* )ucReadPtr, ( size_t ) ulCount );

```

Nothing is done with the value returned!!!  
Is there any ‘#define’ trick here?  
Could I have an outdated file?

I have checked in FreeRTOS 10.2.0, V2.0.11 that I have downloaded and the line is the same.  
The return value is also not used.

Could the feature:  
value 1 = data consumed, 0 = please store data  
be not yet implemented?

thanks

---

<div class="post-metadata">

**Author:** ![htibosch](https://d3iykfbgfh8zhg.cloudfront.net/user_avatar/forums.freertos.org/htibosch/32/62_2.png) [@htibosch](https://forums.freertos.org/u/htibosch)\
**Post date:** [April 15, 2019, 5:00pm UTC](https://forums.freertos.org/t/freertos-ip-callbacks/7786/11 "2019-04-15T17:00:50Z")

</div>

**[heinbali01](https://sourceforge.net/u/heinbali01/)** wrote on [Monday, April 15, 2019](https://sourceforge.net/p/freertos/discussion/382005/thread/b3ece8be94/#3f92):

Oops, my bad: there has been an earlier version in which the return code was used. But there was a problem with that solution and then we decided to always remove the data from the RX stream buffer:

```auto
    pxSocket->u.xTCP.pxHandleReceive( (Socket_t *)pxSocket, ( void* )ucReadPtr, ( size_t ) ulCount );
    uxStreamBufferGet( pxStream, 0ul, NULL, ( size_t ) ulCount, pdFALSE );

```

It was a theretical problem: suppose that the Receive handler function returns 0, 1, 0, 1, The wrong data would be kept in the RX buffer.

You can either consume the data within the handler, or copy/store it in a separate circular buffer, and pass it to the task. I’m sorry about that.

---

<div class="post-metadata">

**Author:** ![system](https://d2v6vdsk2p900z.cloudfront.net/original/1X/7fc8fdb729c645aab5b20282bbe34e57cb407be6.jpeg) [@system](https://forums.freertos.org/u/system)\
**Post date:** [April 16, 2019, 6:18am UTC](https://forums.freertos.org/t/freertos-ip-callbacks/7786/12 "2019-04-16T06:18:02Z")

</div>

**[eduardo1966](https://sourceforge.net/u/eduardo1966/)** wrote on [Tuesday, April 16, 2019](https://sourceforge.net/p/freertos/discussion/382005/thread/b3ece8be94/#e562):

Got it 🙂  
Could I suggest that maybe it is better to do it the other way. Never to take the data out.  
In this way no buffer needs to be allocated by using pvPortMalloc in the callback function:

```auto
    pData_new = pvPortMalloc ( xLength );
    memcpy ( pData_new, pData, xLength );

```

Instead this is done in the receiver task:

```auto
    pData_new = pvPortMalloc ( Callback_Message.Receive.xLength );
    receivedData = FreeRTOS_recv ( Callback_Message.Receive.xSocket, pData_new/*pvBuffer*/, Callback_Message.Receive.xLength, 0/*xFlags*/ );

```

This would make the time inside the callback function smaller and deterministic. The allocation method can be time underterministic (I think there are some heap management methods in FreeRTOS that are deterministic but others aren’t…).  
Instead of allocating memory one could declare a static variable of say 100 bytes, big enough to conatin any legal message. This would make the code faster and deterministic.

Another way would be to use a setsockopt call:

```auto
reeRTOS_setsockopt ( IPreceiver_Socket, 0, FREERTOS_SO_TCP_RECV_HANDLER_CONSUME_DATA, 0 or 1 ... );

```

Before setting the callback function change FREERTOS\_SO\_TCP\_RECV\_HANDLER\_CONSUME\_DATA to 0, don’t consume or 1, consume.  
If this is called after setting the callback function, it has no effect.  
Default value could be 0, don’t consume.

---

<div class="post-metadata">

**Author:** ![htibosch](https://d3iykfbgfh8zhg.cloudfront.net/user_avatar/forums.freertos.org/htibosch/32/62_2.png) [@htibosch](https://forums.freertos.org/u/htibosch)\
**Post date:** [April 16, 2019, 5:22pm UTC](https://forums.freertos.org/t/freertos-ip-callbacks/7786/13 "2019-04-16T17:22:53Z")

</div>

**[heinbali01](https://sourceforge.net/u/heinbali01/)** wrote on [Tuesday, April 16, 2019](https://sourceforge.net/p/freertos/discussion/382005/thread/b3ece8be94/#a7d3):

Hi Eduardo, personally I would not make a new socket option, just introduce a new macro `ipconfigTCP_RECV_HANDLER_CONSUMES_DATA`, which is non-zero by default.

I’m afraid that I don’t have enough time to transform this proposal into a pull-request. It needs a bit of study within the function `lTCPAddRxdata()`, and good testing.

If I were you, I would either use select() or associate a semaphore with the sockets, and store each socket handle in a struct. The struct’s will tell in what stage the connection is.

---

<div class="post-metadata">

**Author:** ![system](https://d2v6vdsk2p900z.cloudfront.net/original/1X/7fc8fdb729c645aab5b20282bbe34e57cb407be6.jpeg) [@system](https://forums.freertos.org/u/system)\
**Post date:** [April 17, 2019, 7:53am UTC](https://forums.freertos.org/t/freertos-ip-callbacks/7786/14 "2019-04-17T07:53:02Z")

</div>

**[eduardo1966](https://sourceforge.net/u/eduardo1966/)** wrote on [Wednesday, April 17, 2019](https://sourceforge.net/p/freertos/discussion/382005/thread/b3ece8be94/#6057):

It seems however there is a timing problem.  
We are running FreeRTOS+IP on a Atmel Cortex M7. The other end is a Linux system with a much faster processor.  
Using the callback mechanism it seems that the first message sent just after establishing connection, is lost.  
When a connection is established the callback function is called:

```auto
static void Callback_OnConnectDisconnect ( Socket_t xSocket, BaseType_t ulConnected )
{
    Callback_Message_t Callback_Message;

    Callback_Message.type = Callback_Connect_Disconnect;
    Callback_Message.Connect_Disconnect.xSocket = xSocket;
    Callback_Message.Connect_Disconnect.ulConnected = ulConnected;

    if ( xQueueSend ( xQueue_Callback, (void*) &Callback_Message, 0 ) != pdPASS )
        /* In case there is no space in the Queue,
         * we should print something to the service port but we are inside FreeRTOS IP so it's better just increment a counter.
         * The printing will take place in the main loop.
         */
        xQueue_Callback_Errors++;
}

```

Which creates a message to be processed by the IP receiver task that is waiting on a queue

```auto
        if ( xQueueReceive ( xQueue_Callback, &Callback_Message, portMAX_DELAY ) )
        {
            switch ( Callback_Message.type )
            {
                case Callback_Connect_Disconnect:
                {
                    F_TCP_UDP_Handler_t Handler_OnReceive;
                    if ( Callback_Message.Connect_Disconnect.ulConnected )
                    {
                        IPreceiver_Socket = FreeRTOS_accept ( IPaccept_Socket, &xClient, &xSize );

                        /* Install a callback for receiving TCP data. */
                        Handler_OnReceive.pxOnTCPReceive = Callback_OnReceive;
                        FreeRTOS_setsockopt ( IPreceiver_Socket, 0, FREERTOS_SO_TCP_RECV_HANDLER, (void *) &Handler_OnReceive, sizeof(Handler_OnReceive) );

```

So there is some time until FreeRTOS\_setsockopt is called to set the callback function for FREERTOS\_SO\_TCP\_RECV\_HANDLER.

If on the Linux system a put a delay of 1 second before sending the message it works fine.  
It seems that a message sent before FreeRTOS\_setsockopt is called, is lost.

Any ideas how to solve this?  
thanks

---

<div class="post-metadata">

**Author:** ![htibosch](https://d3iykfbgfh8zhg.cloudfront.net/user_avatar/forums.freertos.org/htibosch/32/62_2.png) [@htibosch](https://forums.freertos.org/u/htibosch)\
**Post date:** [April 17, 2019, 9:14am UTC](https://forums.freertos.org/t/freertos-ip-callbacks/7786/15 "2019-04-17T09:14:51Z")

</div>

**[heinbali01](https://sourceforge.net/u/heinbali01/)** wrote on [Wednesday, April 17, 2019](https://sourceforge.net/p/freertos/discussion/382005/thread/b3ece8be94/#d7fd):

Eduardo, I’m attaching the source code for a telnet server.

It doesn’t use any blocking code, in stead, it blocks on a semaphore.

Only `xTelnet.xParentSocket` is attached to the semaphore. All child sockets will inherit this setting.

I just tested the module with real hardware, and it works well. I hope that this gives ideas for a different approach.

---

<div class="post-metadata">

**Author:** ![htibosch](https://d3iykfbgfh8zhg.cloudfront.net/user_avatar/forums.freertos.org/htibosch/32/62_2.png) [@htibosch](https://forums.freertos.org/u/htibosch)\
**Post date:** [April 17, 2019, 9:18am UTC](https://forums.freertos.org/t/freertos-ip-callbacks/7786/16 "2019-04-17T09:18:29Z")

</div>

**[heinbali01](https://sourceforge.net/u/heinbali01/)** wrote on [Wednesday, April 17, 2019](https://sourceforge.net/p/freertos/discussion/382005/thread/b3ece8be94/#8038):

About your last post: it is possible that the first packet comes immediately after the SYN/ACK, and that the first data packet gets lost because the recv handler isn’t set yet.  
Solution: set the socket option `FREERTOS_SO_TCP_RECV_HANDLER` on the parent socket. It will be automatically inherited by all child sockets. That should solve the “timing problem”.

---

<div class="post-metadata">

**Author:** ![htibosch](https://d3iykfbgfh8zhg.cloudfront.net/user_avatar/forums.freertos.org/htibosch/32/62_2.png) [@htibosch](https://forums.freertos.org/u/htibosch)\
**Post date:** [April 17, 2019, 9:28am UTC](https://forums.freertos.org/t/freertos-ip-callbacks/7786/17 "2019-04-17T09:28:02Z")

</div>

**[heinbali01](https://sourceforge.net/u/heinbali01/)** wrote on [Wednesday, April 17, 2019](https://sourceforge.net/p/freertos/discussion/382005/thread/b3ece8be94/#22ca):

While 2 posts are waiting for moderation…, I try it from a different IP-address.  
Please apply `FREERTOS_SO_TCP_RECV_HANDLER` to the parent socket. It will be inherited by the child sockets and you won’t loose the first packet.  
Also I attached a ZIP file as an example of using semaphores.

---

<div class="post-metadata">

**Author:** ![system](https://d2v6vdsk2p900z.cloudfront.net/original/1X/7fc8fdb729c645aab5b20282bbe34e57cb407be6.jpeg) [@system](https://forums.freertos.org/u/system)\
**Post date:** [April 17, 2019, 10:26am UTC](https://forums.freertos.org/t/freertos-ip-callbacks/7786/18 "2019-04-17T10:26:51Z")

</div>

**[eduardo1966](https://sourceforge.net/u/eduardo1966/)** wrote on [Wednesday, April 17, 2019](https://sourceforge.net/p/freertos/discussion/382005/thread/b3ece8be94/#53be):

It works, thanks.  
Another bug bites the dust 🙂
