Can't connect sockets to send data with FreeRTOS-TCP

Hello,

I work with the microcontroller SAM3X8E and I develop the program with Atmel Studio 7.

I am a beginner of FreeRTOS-Plus6TCP. I want to send some data from my Computer to my programming board thanks to ethernet bus TCP/IP.
To do that I have include in the program of my programming board FreeRTOS-Plus-TCP (v202012.01). For the computer I use a python program with python socket library.

I can ping my card but the issue is that when I try to connect the socket of my computer (the client) to the socket of my programming board (the server) I have timeout error…

This is the program of my computer :

import socket

IP_PORT = 5050
BAUD_RATE = int(115200)
arduino_IP_address = "192.168.1.40" //It's the IP adress of my programming board (I can ping my card with this IP)

try
     if client is None:
         client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
         client.settimeout(5)
         client.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
         client.connect((arduino_IP_address, IP_PORT))
except OSError as err:
         print(err)

This is what I get when I launch this program :
image

This is the program of my programming board :

void task_ethernet(void *param)
{
	//Wait for the IP-stack run one time
	vTaskDelay(pdMS_TO_TICKS(10));

	/* Variables */
	Socket_t xListeningSocket, xConnectedSocket;
	static const TickType_t xReceiveTimeOut = 200;
	struct freertos_sockaddr xBindAddress, xClient;
	socklen_t xSize = sizeof(xClient);
	const BaseType_t xBacklog = 20;
	
	/* Creation + check of the socket */
	xListeningSocket = FreeRTOS_socket(FREERTOS_AF_INET, FREERTOS_SOCK_STREAM, FREERTOS_IPPROTO_TCP);
	if(xListeningSocket == FREERTOS_INVALID_SOCKET){
		printf("problem with the socket \r\n");
		return;
	}
	
	/* Set a time out so accept() will just wait for a connection. */
	FreeRTOS_setsockopt(xListeningSocket, 0, FREERTOS_SO_RCVTIMEO, &xReceiveTimeOut, sizeof( xReceiveTimeOut ));
	
	/* Set of the IP port */
	xBindAddress.sin_port = (uint16_t) 5050;
	xBindAddress.sin_port = FreeRTOS_htons(xBindAddress.sin_port);

	/* Bind the socket to the port that the client RTOS task will send to. */
	if(FreeRTOS_bind(xListeningSocket, &xBindAddress, sizeof( xBindAddress )) < 0){
		printf("problem with the bind of the socket \r\n");
		return;
	}
	
	/* Set the socket into a listening state so it can accept connections. */
	if(FreeRTOS_listen(xListeningSocket, xBacklog) < 0){
		printf("problem with the listen mode of the socket \r\n");
		return;
	}
	
	printf("Socket ready \r\n");
	
	static char cRxedData[BUFFER_SIZE];
	BaseType_t lBytesReceived;
	
	uint32_t ul_frm_size = 0;
	
	while(1)
	{
        /* To ping my card */
		if (emac_dev_read(&gs_emac_dev, (uint8_t *) gs_uc_eth_buffer, sizeof(gs_uc_eth_buffer), &ul_frm_size) == EMAC_OK) {
			emac_process_eth_packet((uint8_t *) gs_uc_eth_buffer, ul_frm_size);
		}

		printf("Start");
		/* Wait for incoming connections. */
		xConnectedSocket = FreeRTOS_accept(xListeningSocket, &xClient, &xSize);
		printf("End \r\n");

		if(xConnectedSocket == FREERTOS_INVALID_SOCKET || xConnectedSocket == NULL){
			continue;
		}
		else{
			printf("connected \r\n");
		}
		vTaskDelay(pdMS_TO_TICKS(200));
	}//End while(1)
}

int main(void)
{		
	/* Initialize interrupts */
	irq_initialize_vectors();
	cpu_irq_enable();
	
	/* Initialize the SAM system */
	sysclk_init();
	
	/* Setup of the I/Os, DAC and ADC PINs */
	board_init();

	/* Initialize the console uart */
	configure_console();	
	/* Print of basic informations in the consol uart */
	puts(STRING_HEADER);
	
	/* Setup Ethernet */
	init_eth();
	FreeRTOS_IPInit(gs_uc_ip_address, gs_uc_netmask, gs_uc_gateway_address, gs_uc_DNS_address, gs_uc_mac_address);
	
	/* Tasks */
	xTaskCreate(task_ethernet, "Ethernet_task", 2500, NULL, 4, &point_task_eth);
	
	//Wait for the cable ethernet to be plug
	while(ethernet_phy_auto_negotiate(EMAC, BOARD_EMAC_PHY_ADDR) != EMAC_OK);
	while(ethernet_phy_set_link(EMAC, BOARD_EMAC_PHY_ADDR, 1) != EMAC_OK);
	
	/* Scheduler */
	vTaskStartScheduler();
}

The socket is well create but the FreeRTOS_accept(…) always return me a NULL socket.
I put somes printf in this function and the way follows is always the same :

Socket_t FreeRTOS_accept( Socket_t xServerSocket, struct freertos_sockaddr * pxAddress, socklen_t * pxAddressLength )
{
        FreeRTOS_Socket_t * pxSocket = ( FreeRTOS_Socket_t * ) xServerSocket;
        FreeRTOS_Socket_t * pxClientSocket = NULL;
        TickType_t xRemainingTime;
        BaseType_t xTimed = pdFALSE, xAsk = pdFALSE;
        TimeOut_t xTimeOut;
        IPStackEvent_t xAskEvent;

        if( prvValidSocket( pxSocket, FREERTOS_IPPROTO_TCP, pdTRUE ) == pdFALSE )
        {
            /* Not a valid socket or wrong type */
            pxClientSocket = FREERTOS_INVALID_SOCKET;
        }
        else if( ( pxSocket->u.xTCP.bits.bReuseSocket == pdFALSE_UNSIGNED ) &&
                 ( pxSocket->u.xTCP.ucTCPState != ( uint8_t ) eTCP_LISTEN ) )
        {
            /* Parent socket is not in listening mode */
            pxClientSocket = FREERTOS_INVALID_SOCKET;
        }
        else
        {
            /* Loop will stop with breaks. */
            for( ; ; )
            {
                /* Is there a new client? */
                vTaskSuspendAll();
				{
					printf("lol");
					if( pxSocket->u.xTCP.bits.bReuseSocket == pdFALSE_UNSIGNED )
					{
						printf("lol2_1");
						pxClientSocket = pxSocket->u.xTCP.pxPeerSocket;
					}
					else
					{
						printf("lol2_2");
						pxClientSocket = pxSocket;
					}
					printf("lol3");
					if( pxClientSocket != NULL )
					{
						printf("lol4");
						pxSocket->u.xTCP.pxPeerSocket = NULL;
						
						/* Is it still not taken ? */
						if( pxClientSocket->u.xTCP.bits.bPassAccept != pdFALSE_UNSIGNED )
						{
							printf("lol5_1");
							pxClientSocket->u.xTCP.bits.bPassAccept = pdFALSE;
						}
						else
						{
							printf("lol5_2");
							pxClientSocket = NULL;
						}
					}
					printf("lol6");
				}
                xTaskResumeAll();
				printf("lol7");

                if( pxClientSocket != NULL )
                {
					printf("lol8");
                    if( pxAddress != NULL )
                    {
                        /* IP address of remote machine. */
                        pxAddress->sin_addr = FreeRTOS_ntohl( pxClientSocket->u.xTCP.ulRemoteIP );

                        /* Port on remote machine. */
                        pxAddress->sin_port = FreeRTOS_ntohs( pxClientSocket->u.xTCP.usRemotePort );
                    }

                    if( pxAddressLength != NULL )
                    {
                        *pxAddressLength = sizeof( *pxAddress );
                    }

                    if( pxSocket->u.xTCP.bits.bReuseSocket == pdFALSE_UNSIGNED )
                    {
                        xAsk = pdTRUE;
                    }
                }
				printf("lol9");
                if( xAsk != pdFALSE )
                {
                    /* Ask to set an event in 'xEventGroup' as soon as a new
                     * client gets connected for this listening socket. */
                    xAskEvent.eEventType = eTCPAcceptEvent;
                    xAskEvent.pvData = pxSocket;
                    ( void ) xSendEventStructToIPTask( &xAskEvent, portMAX_DELAY );
                }
				printf("lol10");
                if( pxClientSocket != NULL )
                {
					printf("lol11");
                    break;
                }

                if( xTimed == pdFALSE )
                {
					printf("lol12");
                    /* Only in the first round, check for non-blocking */
                    xRemainingTime = pxSocket->xReceiveBlockTime;

                    if( xRemainingTime == ( TickType_t ) 0 )
                    {
						printf("lol13");
                        break;
                    }
					
                    /* Don't get here a second time */
                    xTimed = pdTRUE;
					
                    /* Fetch the current time */
                    vTaskSetTimeOutState( &xTimeOut );
                }
				printf("lol14");
                /* Has the timeout been reached? */
                if( xTaskCheckForTimeOut( &xTimeOut, &xRemainingTime ) != pdFALSE )
                {
					printf("lol15");
                    break;
                }
				printf("lol16");
				
                /* Go sleeping until we get any down-stream event */
                ( void ) xEventGroupWaitBits( pxSocket->xEventGroup, ( EventBits_t ) eSOCKET_ACCEPT, pdTRUE /*xClearOnExit*/, pdFALSE /*xWaitAllBits*/, xRemainingTime );
				printf("lol17");
            }
        }
        printf("lol18");
        return pxClientSocket;
}

I always got this (even when I launch my computer program to connect to my programming board) :
Socket ready (mean the socket is well create)
Start (just befor the FreeRTOS_accept(…) in my ethernet_task)
lol lol2_1 lol3 lol6 lol7 lol9 lol10 lol12 lol14 lol16 lol17
lol lol2_1 lol3 lol6 lol7 lol9 lol10 lol14 lol15 lol18
End (after the FreeRTOS_accept(…) in my ethernet_task)

Do you have any idea of the problem ?

Please also post the code where you create the socket and call FreeRTOS_Accept().

I post all the code, I create the socket in the function task_ethernet(…) (2nd code part in my post)

You call FreeRTOS_listen() with a back-log of 20. That means that the socket will accept up to 20 clients. In case the device runs out of resources, less clients can connect.

Note that your python script only connects to the server, it never sends a shutdown command. When I try the script, I can see that the socket in the device remains open after the python script is finished.

I am little experienced with python, but I came up with this script:

import socket
from time import sleep

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(("192.168.2.17", 23))
sock.sendall("Hello world".encode());
data = sock.recv(1024)
sleep(1)
sock.shutdown(socket.SHUT_RDWR)
sleep(1)
sock.close()

print ("Received")
print (repr(data))

( using python 3.7.3 )

It works well, except that I do not see a gracious closure of the connection. My python session now ends with a RST packet sent by my laptop. But at least my embedded device now closes the Telnet socket ( port 23 ).

Have you looked with Wireshark already? That reveals everything, much better than printf’s.
If you want you can make a PCAP, zip it, and attach it to your post.

Thank you Htibosch for your answer !

I am not at my company tooday so I will try to reduce the back-log use for FreeRTOS_listen() Monday.

Yeah, my real python script is bigger but for the post I reduce it because I can’t connect my socket so I only put the part when I try to connect…

I didn’t try to see ethernet packets with wiresharks I will attach you the file Monday morning too !

But i really don’t understan why I can’t connect my card to my computer however I create socket in the both part… FreeRTOS_accept() return always NULL socket and follow the same way as if trying to connect with my PC doesn’t change anything.

I am 100% sure that is not a port problem because I try to connect without firewall, after add the port (5050) to the incoming / outgoing connections accepted by my firewall but that don’t change anything.

Hello everyone,

I try to reduce my back-log and I put it at 1 because I just want one connection in the same time with my socket server. I still have a timeout error with my socket client when I try to connect it…

This is what I get with my python programme when I try to conenct my socket :

And this is what I get when I try to use your python script :

but with your script too the socket never pass the sock.connect(). I have this error :
TimeoutError: [WinError 10060] Une tentative de connexion a échoué car le parti connecté n’a pas répondu convenablement au-delà d’une certaine durée ou une connexion établie a échoué car l’hôte de connexion n’a pas répondu

I can see that I never get the answer (SYN, ACK) from my server after that the client try to connect. Maybe this is why I can’t connect my socket. But I follow strictly the methode shows in the tuto of FreeRTOS-TCP.

When I look in detail the TCP SYN packet I can see that everything looks well :

There is the good mac adress for the both (src and dst), there is the good Ip adress too and it’s the good port which try to be use (5050)…

When I look at internet why a TCP server don’t send a SYN,ACK after a SYN from a client, I can see that it’s a problem with some configuration. I try to desactivate the windowing mechanism but that don’t change anything…

This is my file FreeRTOSIPConfig.h (I know it’s a bit big but I am lost) :

/*****************************************************************************
*
* See the following URL for configuration information.
* http://www.freertos.org/FreeRTOS-Plus/FreeRTOS_Plus_TCP/TCP_IP_Configuration.html
*
*****************************************************************************/

#ifndef FREERTOS_IP_CONFIG_H
#define FREERTOS_IP_CONFIG_H

#define _static

#define ipconfigUSE_ARP_REMOVE_ENTRY       0	//1
#define ipconfigUSE_ARP_REVERSED_LOOKUP    0	//1	

/* Set to 1 to print out debug messages.  If ipconfigHAS_DEBUG_PRINTF is set to
 * 1 then FreeRTOS_debug_printf should be defined to the function used to print
 * out the debugging messages. */
#define ipconfigHAS_DEBUG_PRINTF           0
#if ( ipconfigHAS_DEBUG_PRINTF == 1 )
    #define FreeRTOS_debug_printf(X)    configPRINTF(X)
#endif

/* Set to 1 to print out non debugging messages, for example the output of the
 * FreeRTOS_netstat() command, and ping replies.  If ipconfigHAS_PRINTF is set to 1
 * then FreeRTOS_printf should be set to the function used to print out the
 * messages. */
#define ipconfigHAS_PRINTF    1
#if ( ipconfigHAS_PRINTF == 1 )
    #define FreeRTOS_printf( X )    configPRINTF( X )
#endif

/* Define the byte order of the target MCU (the MCU FreeRTOS+TCP is executing
 * on).  Valid options are pdFREERTOS_BIG_ENDIAN and pdFREERTOS_LITTLE_ENDIAN. */
#define ipconfigBYTE_ORDER							pdFREERTOS_LITTLE_ENDIAN		//ou pdFREERTOS_BIG_ENDIAN ?

/* If the network card/driver includes checksum offloading (IP/TCP/UDP checksums)
 * then set ipconfigDRIVER_INCLUDED_RX_IP_CHECKSUM to 1 to prevent the software
 * stack repeating the checksum calculations. */
#define ipconfigDRIVER_INCLUDED_RX_IP_CHECKSUM		1

/* Several API's will block until the result is known, or the action has been
 * performed, for example FreeRTOS_send() and FreeRTOS_recv().  The timeouts can be
 * set per socket, using setsockopt().  If not set, the times below will be
 * used as defaults. */
#define ipconfigSOCK_DEFAULT_RECEIVE_BLOCK_TIME		(pdMS_TO_TICKS(200))
#define ipconfigSOCK_DEFAULT_SEND_BLOCK_TIME		(pdMS_TO_TICKS(200))

/* Include support for DNS caching.  For TCP, having a small DNS cache is very
 * useful.  When a cache is present, ipconfigDNS_REQUEST_ATTEMPTS can be kept low
 * and also DNS may use small timeouts.  If a DNS reply comes in after the DNS
 * socket has been destroyed, the result will be stored into the cache.  The next
 * call to FreeRTOS_gethostbyname() will return immediately, without even creating
 * a socket.
 */
#define ipconfigUSE_DNS_CACHE						(1)
#define ipconfigDNS_CACHE_ADDRESSES_PER_ENTRY		(6)
#define ipconfigDNS_REQUEST_ATTEMPTS				(2)

/* The IP stack executes it its own task (although any application task can make
 * use of its services through the published sockets API). ipconfigUDP_TASK_PRIORITY
 * sets the priority of the task that executes the IP stack.  The priority is a
 * standard FreeRTOS task priority so can take any value from 0 (the lowest
 * priority) to (configMAX_PRIORITIES - 1) (the highest priority).
 * configMAX_PRIORITIES is a standard FreeRTOS configuration parameter defined in
 * FreeRTOSConfig.h, not FreeRTOSIPConfig.h. Consideration needs to be given as to
 * the priority assigned to the task executing the IP stack relative to the
 * priority assigned to tasks that use the IP stack. */
#define ipconfigIP_TASK_PRIORITY					(4)

/* The size, in words (not bytes), of the stack allocated to the FreeRTOS+TCP
 * task.  This setting is less important when the FreeRTOS Win32 simulator is used
 * as the Win32 simulator only stores a fixed amount of information on the task
 * stack.  FreeRTOS includes optional stack overflow detection, see:
 * http://www.freertos.org/Stacks-and-stack-overflow-checking.html. */
#define ipconfigIP_TASK_STACK_SIZE_WORDS			(configMINIMAL_STACK_SIZE * 5)

/* ipconfigRAND32() is called by the IP stack to generate random numbers for
 * things such as a DHCP transaction number or initial sequence number.  Random
 * number generation is performed via this macro to allow applications to use their
 * own random number generation method.  For example, it might be possible to
 * generate a random number by sampling noise on an analogue input. */
extern uint32_t ulRand();
#define ipconfigRAND32()    ulRand()

/* If ipconfigUSE_NETWORK_EVENT_HOOK is set to 1 then FreeRTOS+TCP will call the
 * network event hook at the appropriate times.  If ipconfigUSE_NETWORK_EVENT_HOOK
 * is not set to 1 then the network event hook will never be called. See:
 * http://www.FreeRTOS.org/FreeRTOS-Plus/FreeRTOS_Plus_UDP/API/vApplicationIPNetworkEventHook.shtml.
 */
#define ipconfigUSE_NETWORK_EVENT_HOOK				0

/* Sockets have a send block time attribute.  If FreeRTOS_sendto() is called but
 * a network buffer cannot be obtained then the calling task is held in the Blocked
 * state (so other tasks can continue to executed) until either a network buffer
 * becomes available or the send block time expires.  If the send block time expires
 * then the send operation is aborted.  The maximum allowable send block time is
 * capped to the value set by ipconfigMAX_SEND_BLOCK_TIME_TICKS.  Capping the
 * maximum allowable send block time prevents prevents a deadlock occurring when
 * all the network buffers are in use and the tasks that process (and subsequently
 * free) the network buffers are themselves blocked waiting for a network buffer.
 * ipconfigMAX_SEND_BLOCK_TIME_TICKS is specified in RTOS ticks.  A time in
 * milliseconds can be converted to a time in ticks by dividing the time in
 * milliseconds by portTICK_PERIOD_MS. */
#define ipconfigUDP_MAX_SEND_BLOCK_TIME_TICKS		(pdMS_TO_TICKS(200))	//(pdMS_TO_TICKS(5000))

/* If ipconfigUSE_DHCP is 1 then FreeRTOS+TCP will attempt to retrieve an IP
 * address, netmask, DNS server address and gateway address from a DHCP server.  If
 * ipconfigUSE_DHCP is 0 then FreeRTOS+TCP will use a static IP address.  The
 * stack will revert to using the static IP address even when ipconfigUSE_DHCP is
 * set to 1 if a valid configuration cannot be obtained from a DHCP server for any
 * reason.  The static configuration used is that passed into the stack by the
 * FreeRTOS_IPInit() function call. */
#define ipconfigUSE_DHCP							0	//1
#define ipconfigDHCP_REGISTER_HOSTNAME				0	//1
#define ipconfigDHCP_USES_UNICAST					0	//1

/* If ipconfigDHCP_USES_USER_HOOK is set to 1 then the application writer must
 * provide an implementation of the DHCP callback function,
 * xApplicationDHCPUserHook(). */
#define ipconfigUSE_DHCP_HOOK						0

/* When ipconfigUSE_DHCP is set to 1, DHCP requests will be sent out at
 * increasing time intervals until either a reply is received from a DHCP server
 * and accepted, or the interval between transmissions reaches
 * ipconfigMAXIMUM_DISCOVER_TX_PERIOD.  The IP stack will revert to using the
 * static IP address passed as a parameter to FreeRTOS_IPInit() if the
 * re-transmission time interval reaches ipconfigMAXIMUM_DISCOVER_TX_PERIOD without
 * a DHCP reply being received. */
#define ipconfigMAXIMUM_DISCOVER_TX_PERIOD \
    (120000U / portTICK_PERIOD_MS)

/* The ARP cache is a table that maps IP addresses to MAC addresses.  The IP
 * stack can only send a UDP message to a remove IP address if it knowns the MAC
 * address associated with the IP address, or the MAC address of the router used to
 * contact the remote IP address.  When a UDP message is received from a remote IP
 * address the MAC address and IP address are added to the ARP cache.  When a UDP
 * message is sent to a remote IP address that does not already appear in the ARP
 * cache then the UDP message is replaced by a ARP message that solicits the
 * required MAC address information.  ipconfigARP_CACHE_ENTRIES defines the maximum
 * number of entries that can exist in the ARP table at any one time. */
#define ipconfigARP_CACHE_ENTRIES					6	//Essayer avec 1

/* ARP requests that do not result in an ARP response will be re-transmitted a
 * maximum of ipconfigMAX_ARP_RETRANSMISSIONS times before the ARP request is
 * aborted. */
#define ipconfigMAX_ARP_RETRANSMISSIONS				(5)

/* ipconfigMAX_ARP_AGE defines the maximum time between an entry in the ARP
 * table being created or refreshed and the entry being removed because it is stale.
 * New ARP requests are sent for ARP cache entries that are nearing their maximum
 * age.  ipconfigMAX_ARP_AGE is specified in tens of seconds, so a value of 150 is
 * equal to 1500 seconds (or 25 minutes). */
#define ipconfigMAX_ARP_AGE							150

/* Implementing FreeRTOS_inet_addr() necessitates the use of string handling
 * routines, which are relatively large.  To save code space the full
 * FreeRTOS_inet_addr() implementation is made optional, and a smaller and faster
 * alternative called FreeRTOS_inet_addr_quick() is provided.  FreeRTOS_inet_addr()
 * takes an IP in decimal dot format (for example, "192.168.0.1") as its parameter.
 * FreeRTOS_inet_addr_quick() takes an IP address as four separate numerical octets
 * (for example, 192, 168, 0, 1) as its parameters.  If
 * ipconfigINCLUDE_FULL_INET_ADDR is set to 1 then both FreeRTOS_inet_addr() and
 * FreeRTOS_indet_addr_quick() are available.  If ipconfigINCLUDE_FULL_INET_ADDR is
 * not set to 1 then only FreeRTOS_indet_addr_quick() is available. */
#define ipconfigINCLUDE_FULL_INET_ADDR				1

/* ipconfigNUM_NETWORK_BUFFER_DESCRIPTORS defines the total number of network buffer that
 * are available to the IP stack.  The total number of network buffers is limited
 * to ensure the total amount of RAM that can be consumed by the IP stack is capped
 * to a pre-determinable value. */
#define ipconfigNUM_NETWORK_BUFFER_DESCRIPTORS		60

/* A FreeRTOS queue is used to send events from application tasks to the IP
 * stack.  ipconfigEVENT_QUEUE_LENGTH sets the maximum number of events that can
 * be queued for processing at any one time.  The event queue must be a minimum of
 * 5 greater than the total number of network buffers. */
#define ipconfigEVENT_QUEUE_LENGTH \
    (ipconfigNUM_NETWORK_BUFFER_DESCRIPTORS + 5)

/* The address of a socket is the combination of its IP address and its port
 * number.  FreeRTOS_bind() is used to manually allocate a port number to a socket
 * (to 'bind' the socket to a port), but manual binding is not normally necessary
 * for client sockets (those sockets that initiate outgoing connections rather than
 * wait for incoming connections on a known port number).  If
 * ipconfigALLOW_SOCKET_SEND_WITHOUT_BIND is set to 1 then calling
 * FreeRTOS_sendto() on a socket that has not yet been bound will result in the IP
 * stack automatically binding the socket to a port number from the range
 * socketAUTO_PORT_ALLOCATION_START_NUMBER to 0xffff.  If
 * ipconfigALLOW_SOCKET_SEND_WITHOUT_BIND is set to 0 then calling FreeRTOS_sendto()
 * on a socket that has not yet been bound will result in the send operation being
 * aborted. */
#define ipconfigALLOW_SOCKET_SEND_WITHOUT_BIND		0	//1

/* Defines the Time To Live (TTL) values used in outgoing UDP packets. */
#define ipconfigUDP_TIME_TO_LIVE					128
/* Also defined in FreeRTOSIPConfigDefaults.h. */
#define ipconfigTCP_TIME_TO_LIVE					128

/* USE_TCP: Use TCP and all its features. */
#define ipconfigUSE_TCP								(1)

/* USE_WIN: Let TCP use windowing mechanism. */
#define ipconfigUSE_TCP_WIN							(0)

/* The MTU is the maximum number of bytes the payload of a network frame can
 * contain.  For normal Ethernet V2 frames the maximum MTU is 1500.  Setting a
 * lower value can save RAM, depending on the buffer management scheme used.  If
 * ipconfigCAN_FRAGMENT_OUTGOING_PACKETS is 1 then (ipconfigNETWORK_MTU - 28) must
 * be divisible by 8. */
#define ipconfigNETWORK_MTU							1200U

/* Set ipconfigUSE_DNS to 1 to include a basic DNS client/resolver.  DNS is used
 * through the FreeRTOS_gethostbyname() API function. */
#define ipconfigUSE_DNS								0

/* If ipconfigREPLY_TO_INCOMING_PINGS is set to 1 then the IP stack will
 * generate replies to incoming ICMP echo (ping) requests. */
#define ipconfigREPLY_TO_INCOMING_PINGS				1

/* If ipconfigSUPPORT_OUTGOING_PINGS is set to 1 then the
 * FreeRTOS_SendPingRequest() API function is available. */
#define ipconfigSUPPORT_OUTGOING_PINGS				0

/* If ipconfigSUPPORT_SELECT_FUNCTION is set to 1 then the FreeRTOS_select()
 * (and associated) API function is available. */
#define ipconfigSUPPORT_SELECT_FUNCTION				1

/* If ipconfigFILTER_OUT_NON_ETHERNET_II_FRAMES is set to 1 then Ethernet frames
 * that are not in Ethernet II format will be dropped.  This option is included for
 * potential future IP stack developments. */
#define ipconfigFILTER_OUT_NON_ETHERNET_II_FRAMES	1

/* If ipconfigETHERNET_DRIVER_FILTERS_FRAME_TYPES is set to 1 then it is the
 * responsibility of the Ethernet interface to filter out packets that are of no
 * interest.  If the Ethernet interface does not implement this functionality, then
 * set ipconfigETHERNET_DRIVER_FILTERS_FRAME_TYPES to 0 to have the IP stack
 * perform the filtering instead (it is much less efficient for the stack to do it
 * because the packet will already have been passed into the stack).  If the
 * Ethernet driver does all the necessary filtering in hardware then software
 * filtering can be removed by using a value other than 1 or 0. */
#define ipconfigETHERNET_DRIVER_FILTERS_FRAME_TYPES	1

/* The windows simulator cannot really simulate MAC interrupts, and needs to
 * block occasionally to allow other tasks to run. */
#define configWINDOWS_MAC_INTERRUPT_SIMULATOR_DELAY	(20 / portTICK_PERIOD_MS)

/* Advanced only: in order to access 32-bit fields in the IP packets with
 * 32-bit memory instructions, all packets will be stored 32-bit-aligned,
 * plus 16-bits. This has to do with the contents of the IP-packets: all
 * 32-bit fields are 32-bit-aligned, plus 16-bit. */
#define ipconfigPACKET_FILLER_SIZE					2U

/* Define the size of the pool of TCP window descriptors.  On the average, each
 * TCP socket will use up to 2 x 6 descriptors, meaning that it can have 2 x 6
 * outstanding packets (for Rx and Tx).  When using up to 10 TP sockets
 * simultaneously, one could define TCP_WIN_SEG_COUNT as 120. */
#define ipconfigTCP_WIN_SEG_COUNT					240

/* Each TCP socket has a circular buffers for Rx and Tx, which have a fixed
 * maximum size.  Define the size of Rx buffer for TCP sockets. */
#define ipconfigTCP_RX_BUFFER_LENGTH				(10000)

/* Define the size of Tx buffer for TCP sockets. */
#define ipconfigTCP_TX_BUFFER_LENGTH				(10000)

/* When using call-back handlers, the driver may check if the handler points to
 * real program memory (RAM or flash) or just has a random non-zero value. */
#define ipconfigIS_VALID_PROG_ADDRESS(x)			((x) != NULL)

/* Include support for TCP keep-alive messages. */
//Pour reveiller les socket qui dorment
#define ipconfigTCP_KEEP_ALIVE						(1)
#define ipconfigTCP_KEEP_ALIVE_INTERVAL				(20) /* Seconds. */

/* The socket semaphore is used to unblock the MQTT task. */
#define ipconfigSOCKET_HAS_USER_SEMAPHORE			(0)

#define ipconfigSOCKET_HAS_USER_WAKE_CALLBACK		(1)
#define ipconfigUSE_CALLBACKS						(0)
	

#define portINLINE

void vApplicationMQTTGetKeys( const char ** ppcRootCA,
                              const char ** ppcClientCert,
                              const char ** ppcClientPrivateKey );

#endif /* FREERTOS_IP_CONFIG_H */

Can you see something wrong with my TCP config ?

Hi Pierre,

I assume that wireshark runs on the machine that also executes your client code? Is there a routed network in between or just a switch/hub? Are you able to log the network traffic in the segment where your board sits? It would be useful to see what packets (if at all) leave your board. What you describe hints at some kind of routing issue.

My client code is from my computer so the screen of wireshark is coming from this machine. My server code is from a programming board so I can’t run wireshark.

Between my computer and my programming board I am directly connected with the ethernet cable :

In attachement I add you all the ethernet packet I can see from my computer when I launch the program of my programming board ! (10.0.1.1 is my gateway adress)
ethernet_packet.zip (6.2 KB)

This appears to be a similar issue to this here:

Can you go over that thread and see if there is useful info for you there?

As a test, could you try to make a connection using a terminal program, e.g. puTTY ?
Can you make it connect to 192.168.1.40 port 5050, using a raw interface type?

I am also thinking of a recent issue, but that was slightly different: the packets from the FreeRTOS device were stopped at the PC.
Only after the PC had done a ping to the device, it was allowed to reply.

In your case, the ARP requests seem to arrive well, and the device gives a proper answer (a8:61:0a:ae:82:c1).

An ARP request is a kind of broadcast, all EMACs will hear it.

A TCP packet is a unicast, going to a particular MAC address. Are you sure that your device has set the MAC-address in the EMAC?

About your FreeRTOSIPConfig.h : that looks OK to me.

In his case the programming board is the client and the computer is the server. In my case it’s the opposite.

Even when I ping my server (my card) with my client (my PC) the conenxion socket return the timeout error and no SYN,ACK packet.

To ping my card I don’t use the function of FreeRTOS-TCP. I use function from emac.h directly :

if (emac_dev_read(&gs_emac_dev, (uint8_t *) gs_uc_eth_buffer, sizeof(gs_uc_eth_buffer), &ul_frm_size) == EMAC_OK) {
			emac_process_eth_packet((uint8_t *) gs_uc_eth_buffer, ul_frm_size);
		}

The final solution of his problem was to change of PC… I am not sure it’s the same issue.

How can I do that with puTTY or cmd ? What is the command line ?

I use this command line to set up my MAC adress (to create the socket) :

FreeRTOS_IPInit(gs_uc_ip_address, gs_uc_netmask, gs_uc_gateway_address, gs_uc_DNS_address, gs_uc_mac_address);

And I use this function too (to use emac function to ping my card):

int init_eth(void)
{
	volatile uint32_t ul_delay;
	emac_options_t emac_option;
	
	/* Reset PHY */
	rstc_set_external_reset(RSTC, 13); /* (2^(13+1))/32768 */
	rstc_reset_extern(RSTC);
	
	while (rstc_get_status(RSTC) & RSTC_SR_NRSTL) {
	};
	rstc_set_external_reset(RSTC, 0);  /* restore default */
	
	
	/* Wait for PHY to be ready (CAT811: Max400ms) */
	ul_delay = sysclk_get_cpu_hz() / 1000 / 3 * 400;
	while (ul_delay--);
	
	/* Enable EMAC clock */
	pmc_enable_periph_clk(ID_EMAC);

	/* Fill in EMAC options */
	emac_option.uc_copy_all_frame = 0;
	emac_option.uc_no_boardcast = 0;
	
	memcpy(emac_option.uc_mac_addr, gs_uc_mac_address, sizeof(gs_uc_mac_address));

	gs_emac_dev.p_hw = EMAC;

	/* Init EMAC driver structure */
	emac_dev_init(EMAC, &gs_emac_dev, &emac_option);

	/* Enable Interrupt */
	NVIC_EnableIRQ(EMAC_IRQn);
	
	/* Init MAC PHY driver */
	if (ethernet_phy_init(EMAC, BOARD_EMAC_PHY_ADDR, sysclk_get_cpu_hz()) != EMAC_OK) {
		printf("PHY Initialize ERROR!\r");
		return -1;
	}
}

When I do a nmap scan of my programming board I have the right MAC adress :
image

I don’t understand that statement. Since this is apparently code running on your board, this can not be code to ping something but instead respond to incoming ICMP requests? So you are bypassing the built in layer? Why on earth are you doing that? What is the complete code to know that this is an ICMP request?

If you shortcut the TCP stack, one thing that happens is that you bypass the routing tables. Could it be that the IP address, subnet mask and default gateway configured on your board attempt to route TCP packets to a non existing interface? What is your address configuration?

I did that because I make the ping part before the socket part…
After the ping works well, I work on the socket.

This is part responding to incoming ICMP request :

if (emac_dev_read(&gs_emac_dev, (uint8_t *) gs_uc_eth_buffer, sizeof(gs_uc_eth_buffer), &ul_frm_size) == EMAC_OK) {
			emac_process_eth_packet((uint8_t *) gs_uc_eth_buffer, ul_frm_size);
		}

you can see it in my ethernet_task code (at the beginning of the post).
This is my emac_process_eth_packet(…) function :

/**
 * \brief Process the received EMAC packet.
 *
 * \param p_uc_data  The data to process.
 * \param ul_size The data size.
 */
void emac_process_eth_packet(uint8_t *p_uc_data, uint32_t ul_size)
{
	uint16_t us_pkt_format;

	p_ethernet_header_t p_eth = (p_ethernet_header_t) (p_uc_data);
	p_ip_header_t p_ip_header = (p_ip_header_t) (p_uc_data + ETH_HEADER_SIZE);
	ip_header_t ip_header;
	us_pkt_format = SWAP16(p_eth->et_protlen);

	switch (us_pkt_format) {
	/* ARP Packet format */
	case ETH_PROT_ARP:
		/* Process the ARP packet */
		emac_process_arp_packet(p_uc_data, ul_size);

		break;

	/* IP protocol frame */
	case ETH_PROT_IP:
		/* Backup the header */
		memcpy(&ip_header, p_ip_header, sizeof(ip_header_t));

		/* Process the IP packet */
		emac_process_ip_packet(p_uc_data, ul_size);

		/* Dump the IP header */
		emac_display_ip_packet(&ip_header, ul_size);
		break;

	default:
		printf("=== Default w_pkt_format= 0x%X===\n\r", us_pkt_format);
		break;
	}
}

/* Ethernet */
static uint16_t emac_icmp_checksum(uint16_t *p_buff, uint32_t ul_len)
{
	uint32_t i, ul_tmp;

	for (i = 0, ul_tmp = 0; i < ul_len; i++, p_buff++) {

		ul_tmp += SWAP16(*p_buff);
	}
	ul_tmp = (ul_tmp & 0xffff) + (ul_tmp >> 16);

	return (uint16_t) (~ul_tmp);
}

/**
 * \brief Display the IP packet.
 *
 * \param p_ip_header Pointer to the IP header.
 * \param ul_size    The data size.
 */
static void emac_display_ip_packet(p_ip_header_t p_ip_header, uint32_t ul_size)
{
	printf("======= IP %4d bytes, HEADER ==========\n\r", (int)ul_size);
	printf(" IP Version        = v.%d", (p_ip_header->ip_hl_v & 0xF0) >> 4);
	printf("\n\r Header Length     = %d", p_ip_header->ip_hl_v & 0x0F);
	printf("\n\r Type of service   = 0x%x", p_ip_header->ip_tos);
	printf("\n\r Total IP Length   = 0x%X",
			(((p_ip_header->ip_len) >> 8) & 0xff) +
			(((p_ip_header->ip_len) << 8) & 0xff00));
	printf("\n\r ID                = 0x%X",
			(((p_ip_header->ip_id) >> 8) & 0xff) +
			(((p_ip_header->ip_id) << 8) & 0xff00));
	printf("\n\r Header Checksum   = 0x%X",
			(((p_ip_header->ip_sum) >> 8) & 0xff) +
			(((p_ip_header->ip_sum) << 8) & 0xff00));
	puts("\r Protocol          = ");

	switch (p_ip_header->ip_p) {
	case IP_PROT_ICMP:
		puts("ICMP");
		break;

	case IP_PROT_IP:
		puts("IP");
		break;

	case IP_PROT_TCP:
		puts("TCP");
		break;

	case IP_PROT_UDP:
		puts("UDP");
		break;

	default:
		printf("%d (0x%X)", p_ip_header->ip_p, p_ip_header->ip_p);
		break;
	}

	printf("\n\r IP Src Address    = %d:%d:%d:%d",
			p_ip_header->ip_src[0],
			p_ip_header->ip_src[1],
			p_ip_header->ip_src[2], p_ip_header->ip_src[3]);

	printf("\n\r IP Dest Address   = %d:%d:%d:%d",
			p_ip_header->ip_dst[0],
			p_ip_header->ip_dst[1],
			p_ip_header->ip_dst[2], p_ip_header->ip_dst[3]);
	puts("\n\r----------------------------------------\r");
}

/**
 * \brief Process the received ARP packet; change address and send it back.
 *
 * \param p_uc_data  The data to process.
 * \param ul_size The data size.
 */
static void emac_process_arp_packet(uint8_t *p_uc_data, uint32_t ul_size)
{
	uint32_t i;
	uint8_t ul_rc = EMAC_OK;

	p_ethernet_header_t p_eth = (p_ethernet_header_t) p_uc_data;
	p_arp_header_t p_arp = (p_arp_header_t) (p_uc_data + ETH_HEADER_SIZE);

	if (SWAP16(p_arp->ar_op) == ARP_REQUEST) {
		printf("-- IP  %d.%d.%d.%d\n\r",
				p_eth->et_dest[0], p_eth->et_dest[1],
				p_eth->et_dest[2], p_eth->et_dest[3]);

		printf("-- IP  %d.%d.%d.%d\n\r",
				p_eth->et_src[0], p_eth->et_src[1],
				p_eth->et_src[2], p_eth->et_src[3]);

		/* ARP reply operation */
		p_arp->ar_op = SWAP16(ARP_REPLY);

		/* Fill the destination address and source address */
		for (i = 0; i < 6; i++) {
			/* Swap ethernet destination address and ethernet source address */
			p_eth->et_dest[i] = p_eth->et_src[i];
			p_eth->et_src[i] = gs_uc_mac_address[i];
			p_arp->ar_tha[i] = p_arp->ar_sha[i];
			p_arp->ar_sha[i] = gs_uc_mac_address[i];
		}
		/* Swap the source IP address and the destination IP address */
		for (i = 0; i < 4; i++) {
			p_arp->ar_tpa[i] = p_arp->ar_spa[i];
			p_arp->ar_spa[i] = gs_uc_ip_address[i];
		}
		ul_rc = emac_dev_write(&gs_emac_dev, p_uc_data, ul_size, NULL);
		if (ul_rc != EMAC_OK) {
			printf("E: ARP Send - 0x%x\n\r", ul_rc);
		}
	}
}

/**
 * \brief Process the received IP packet; change address and send it back.
 *
 * \param p_uc_data  The data to process.
 * \param ul_size The data size.
 */
static void emac_process_ip_packet(uint8_t *p_uc_data, uint32_t ul_size)
{
	uint32_t i;
	uint32_t ul_icmp_len;
	int32_t ul_rc = EMAC_OK;

	/* avoid Cppcheck Warning */
	UNUSED(ul_size);

	p_ethernet_header_t p_eth = (p_ethernet_header_t) p_uc_data;
	p_ip_header_t p_ip_header = (p_ip_header_t) (p_uc_data + ETH_HEADER_SIZE);

	p_icmp_echo_header_t p_icmp_echo =
			(p_icmp_echo_header_t) ((int8_t *) p_ip_header +
			ETH_IP_HEADER_SIZE);
	printf("-- IP  %d.%d.%d.%d\n\r", p_eth->et_dest[0], p_eth->et_dest[1],
			p_eth->et_dest[2], p_eth->et_dest[3]);

	printf("-- IP  %d.%d.%d.%d\n\r",
			p_eth->et_src[0], p_eth->et_src[1], p_eth->et_src[2],
			p_eth->et_src[3]);
	switch (p_ip_header->ip_p) {
	case IP_PROT_ICMP:
		if (p_icmp_echo->type == ICMP_ECHO_REQUEST) {
			p_icmp_echo->type = ICMP_ECHO_REPLY;
			p_icmp_echo->code = 0;
			p_icmp_echo->cksum = 0;

			/* Checksum of the ICMP message */
			ul_icmp_len = (SWAP16(p_ip_header->ip_len) - ETH_IP_HEADER_SIZE);
			if (ul_icmp_len % 2) {
				*((uint8_t *) p_icmp_echo + ul_icmp_len) = 0;
				ul_icmp_len++;
			}
			ul_icmp_len = ul_icmp_len / sizeof(uint16_t);

			p_icmp_echo->cksum = SWAP16(
					emac_icmp_checksum((uint16_t *)p_icmp_echo, ul_icmp_len));
			/* Swap the IP destination  address and the IP source address */
			for (i = 0; i < 4; i++) {
				p_ip_header->ip_dst[i] =
						p_ip_header->ip_src[i];
				p_ip_header->ip_src[i] = gs_uc_ip_address[i];
			}
			/* Swap ethernet destination address and ethernet source address */
			for (i = 0; i < 6; i++) {
				/* Swap ethernet destination address and ethernet source address */
				p_eth->et_dest[i] = p_eth->et_src[i];
				p_eth->et_src[i] = gs_uc_mac_address[i];
			}
			/* Send the echo_reply */
			ul_rc = emac_dev_write(&gs_emac_dev, p_uc_data,
					SWAP16(p_ip_header->ip_len) + 14, NULL);
			if (ul_rc != EMAC_OK) {
				printf("E: ICMP Send - 0x%x\n\r", ul_rc);
			}
		}
		break;

	default:
		break;
	}
}

I got this function from example project from Atmel Studio 7.

As my pings works well, I use a really simple Network Interface because I didn’t really understan the utility of this library (NetworkInterface.c) :

/* If ipconfigETHERNET_DRIVER_FILTERS_FRAME_TYPES is set to 1, then the Ethernet
 * driver will filter incoming packets and only pass the stack those packets it
 * considers need processing. */
#if ( ipconfigETHERNET_DRIVER_FILTERS_FRAME_TYPES == 0 )
    #define ipCONSIDER_FRAME_FOR_PROCESSING( pucEthernetBuffer )    eProcessBuffer
#else
    #define ipCONSIDER_FRAME_FOR_PROCESSING( pucEthernetBuffer )    eConsiderFrameForProcessing( ( pucEthernetBuffer ) )
#endif

BaseType_t xNetworkInterfaceInitialise( void )
{
    return pdTRUE;
}

BaseType_t xNetworkInterfaceOutput( NetworkBufferDescriptor_t * const pxNetworkBuffer, BaseType_t xReleaseAfterSend )
{
    return pdTRUE;
}

This is my configuration address ethernet of my PC :

gs_uc_ip_address obviously is the 192.168.1.40, but where are the definitions for gs_uc_netmask and gs_uc_gateway_address?

Yeah sorry :

/** MAC address definition.  The MAC address must be unique on the network. */
#define ETHERNET_CONF_ETHADDR0                        0xA8 //0x00
#define ETHERNET_CONF_ETHADDR1                        0x61 //0x04
#define ETHERNET_CONF_ETHADDR2                        0x0A //0x25
#define ETHERNET_CONF_ETHADDR3                        0xAE //0x1C
#define ETHERNET_CONF_ETHADDR4                        0x82 //0xA0
#define ETHERNET_CONF_ETHADDR5                        0xC1 //0x02

/** The IP address being used. */
#define ETHERNET_CONF_IPADDR0                         192
#define ETHERNET_CONF_IPADDR1                         168
#define ETHERNET_CONF_IPADDR2                         1
#define ETHERNET_CONF_IPADDR3                         40

/** The gateway address being used. */
#define ETHERNET_CONF_GATEWAY_ADDR0                   10
#define ETHERNET_CONF_GATEWAY_ADDR1                   0
#define ETHERNET_CONF_GATEWAY_ADDR2                   1
#define ETHERNET_CONF_GATEWAY_ADDR3                   1

/** The network mask being used. */
#define ETHERNET_CONF_NET_MASK0                       255
#define ETHERNET_CONF_NET_MASK1                       255
#define ETHERNET_CONF_NET_MASK2                       255
#define ETHERNET_CONF_NET_MASK3                       0

/** The DNS server being used. */
#define ETHERNET_CONF_DNS0							0
#define ETHERNET_CONF_DNS1							0
#define ETHERNET_CONF_DNS2							0
#define ETHERNET_CONF_DNS3							0

/** The MAC address used for the test */
static uint8_t gs_uc_mac_address[] =
{ ETHERNET_CONF_ETHADDR0, ETHERNET_CONF_ETHADDR1, ETHERNET_CONF_ETHADDR2, ETHERNET_CONF_ETHADDR3, ETHERNET_CONF_ETHADDR4, ETHERNET_CONF_ETHADDR5 };

/** The IP address used for test (ping ...) */
static uint8_t gs_uc_ip_address[] =
{ ETHERNET_CONF_IPADDR0, ETHERNET_CONF_IPADDR1, ETHERNET_CONF_IPADDR2, ETHERNET_CONF_IPADDR3 };

/** The network mask used for the test */
static uint8_t gs_uc_netmask[] =
{ ETHERNET_CONF_NET_MASK0, ETHERNET_CONF_NET_MASK1, ETHERNET_CONF_NET_MASK2, ETHERNET_CONF_NET_MASK3 };
	
/** The gateway address being used. */
static uint8_t gs_uc_gateway_address[] =
{ ETHERNET_CONF_GATEWAY_ADDR0, ETHERNET_CONF_GATEWAY_ADDR1, ETHERNET_CONF_GATEWAY_ADDR2, ETHERNET_CONF_GATEWAY_ADDR3 };
	
/** The local DNS address being used. */
static uint8_t gs_uc_DNS_address[] =
{ ETHERNET_CONF_DNS0, ETHERNET_CONF_DNS1, ETHERNET_CONF_DNS2, ETHERNET_CONF_DNS3 };

There are several problems in your configuration, the first being that your default gateway is not in your subnet, so if ever you’d need to route outgoing packets to the default gateway, they couldn’t go anywhere.

That shouldn’t be a problem in your case because theoretically, your source and destination are in the same subnet, and the mask is ok, so you wouldn’t need the gateway.

What endianness does your machine have? You should really make it a habit to use htonl,ntohl etc for all network related configurations. It may be the case that the storage of your addresses in memory is incompatible with your endianness.

If I can ping my card, read the mac adress with wireshark and scan nmap that means that the storage is well no ?
I don’t know how to know what is the endianness use in my programming card… I am a beginner of ethernet TCP communication…

I just change all my configuration by adding FreeRTOS_htonl(…), and change my gateway too :

...
/** The gateway address being used. */
#define ETHERNET_CONF_GATEWAY_ADDR0                   FreeRTOS_htonl(192)
#define ETHERNET_CONF_GATEWAY_ADDR1                   FreeRTOS_htonl(168)
#define ETHERNET_CONF_GATEWAY_ADDR2                   FreeRTOS_htonl(1)
#define ETHERNET_CONF_GATEWAY_ADDR3                   FreeRTOS_htonl(5)